]> git.proxmox.com Git - pve-common.git/blame - src/PVE/CLIHandler.pm
bump version to 4.0-26
[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;
11
12use base qw(PVE::RESTHandler);
13
14my $cmddef;
15my $exename;
16
17my $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
edf3d572
DM
37my $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
e143e9d8
DM
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,
edf3d572 62 completion => $complete_command_names,
e143e9d8
DM
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
7fe1f565
DM
110sub 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
e143e9d8
DM
124sub 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
155sub 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
168sub sorted_commands {
169 return sort { ($cmddef->{$a}->[0] cmp $cmddef->{$b}->[0]) || ($a cmp $b)} keys %$cmddef;
170}
171
172sub 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
d8053c08
DM
190my $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
58d9e664
DM
202 my $args = PVE::Tools::split_args($cmdline);
203 my $pos = scalar(@$args) - 2;
d8053c08
DM
204 $pos += 1 if $cmdline =~ m/\s+$/;
205
206 print STDERR "CMDLINE:$pos:$cmdline\n" if $debug;
207
208 return if $pos < 0;
209
210 my $print_result = sub {
211 foreach my $p (@_) {
212 print "$p\n" if $p =~ m/^$cur/;
213 }
214 };
215
216 my $cmd;
217 if ($simple_cmd) {
218 $cmd = $simple_cmd;
219 } else {
220 if ($pos == 0) {
221 &$print_result(keys %$cmddef);
222 return;
223 }
58d9e664 224 $cmd = $args->[1];
d8053c08
DM
225 }
226
227 my $def = $cmddef->{$cmd};
228 return if !$def;
229
230 print STDERR "CMDLINE1:$pos:$cmdline\n" if $debug;
231
232 my $skip_param = {};
233
234 my ($class, $name, $arg_param, $uri_param) = @$def;
235 $arg_param //= [];
236 $uri_param //= {};
237
d90a2fd0
DM
238 $arg_param = [ $arg_param ] if !ref($arg_param);
239
d8053c08
DM
240 map { $skip_param->{$_} = 1; } @$arg_param;
241 map { $skip_param->{$_} = 1; } keys %$uri_param;
242
243 my $fpcount = scalar(@$arg_param);
244
245 my $info = $class->map_method_by_name($name);
246
247 my $schema = $info->{parameters};
248 my $prop = $schema->{properties};
249
250 my $print_parameter_completion = sub {
251 my ($pname) = @_;
252 my $d = $prop->{$pname};
253 if ($d->{completion}) {
254 my $vt = ref($d->{completion});
255 if ($vt eq 'CODE') {
58d9e664 256 my $res = $d->{completion}->($cmd, $pname, $cur, $args);
d8053c08
DM
257 &$print_result(@$res);
258 }
259 } elsif ($d->{type} eq 'boolean') {
260 &$print_result('0', '1');
261 } elsif ($d->{enum}) {
262 &$print_result(@{$d->{enum}});
263 }
264 };
265
266 # positional arguments
267 $pos += 1 if $simple_cmd;
268 if ($fpcount && $pos <= $fpcount) {
269 my $pname = $arg_param->[$pos -1];
270 &$print_parameter_completion($pname);
271 return;
272 }
273
274 my @option_list = ();
275 foreach my $key (keys %$prop) {
276 next if $skip_param->{$key};
277 push @option_list, "--$key";
278 }
279
280 if ($cur =~ m/^-/) {
281 &$print_result(@option_list);
282 return;
283 }
284
285 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
286 my $pname = $1;
287 &$print_parameter_completion($pname);
288 return;
289 }
290
291 &$print_result(@option_list);
292};
293
1f130ba6
DM
294sub verify_api {
295 my ($class) = @_;
296
297 # simply verify all registered methods
298 PVE::RESTHandler::validate_method_schemas();
299}
300
8f3712f8
DM
301my $get_exe_name = sub {
302 my ($class) = @_;
303
304 my $name = $class;
305 $name =~ s/^.*:://;
306 $name =~ s/_/-/g;
307
308 return $name;
309};
310
c45707a0
DM
311sub generate_bash_completions {
312 my ($class) = @_;
313
314 # generate bash completion config
315
8f3712f8 316 $exename = &$get_exe_name($class);
c45707a0
DM
317
318 print <<__EOD__;
319# $exename bash completion
320
321# see http://tiswww.case.edu/php/chet/bash/FAQ
322# and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
323# this modifies global var, but I found no better way
324COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
325
326complete -C '$exename bashcomplete' $exename
327__EOD__
328}
329
7fe1f565 330sub find_cli_class_source {
8f3712f8 331 my ($name) = @_;
7fe1f565
DM
332
333 my $filename;
334
8f3712f8
DM
335 $name =~ s/-/_/g;
336
337 my $cpath = "PVE/CLI/${name}.pm";
338 my $spath = "PVE/Service/${name}.pm";
7fe1f565 339 foreach my $p (@INC) {
edf3d572
DM
340 foreach my $s (($cpath, $spath)) {
341 my $testfn = "$p/$s";
342 if (-f $testfn) {
343 $filename = $testfn;
344 last;
345 }
7fe1f565 346 }
edf3d572 347 last if defined($filename);
7fe1f565
DM
348 }
349
350 return $filename;
351}
352
1f130ba6
DM
353sub generate_pod_manpage {
354 my ($class, $podfn) = @_;
355
8f3712f8 356 $exename = &$get_exe_name($class);
1f130ba6 357
7fe1f565 358 $podfn = find_cli_class_source($exename) if !defined($podfn);
1f130ba6
DM
359
360 die "unable to find source for class '$class'" if !$podfn;
361
7fe1f565
DM
362 no strict 'refs';
363 my $def = ${"${class}::cmddef"};
364
bb958629 365 if (ref($def) eq 'ARRAY') {
7fe1f565
DM
366 print_simple_pod_manpage($podfn, @$def);
367 } else {
368 $cmddef = $def;
edf3d572
DM
369
370 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
371
7fe1f565
DM
372 print_pod_manpage($podfn);
373 }
1f130ba6
DM
374}
375
edf3d572 376sub run_cli {
7fe1f565 377 my ($class, $pwcallback, $podfn, $preparefunc) = @_;
93ddd7bc
DM
378
379 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
380
8f3712f8 381 $exename = &$get_exe_name($class);
93ddd7bc
DM
382
383 initlog($exename);
384
93ddd7bc 385
2a8ced7b
DM
386 if ($class !~ m/^PVE::Service::/) {
387 die "please run as root\n" if $> != 0;
93ddd7bc 388
2a8ced7b
DM
389 PVE::INotify::inotify_init();
390
391 my $rpcenv = PVE::RPCEnvironment->init('cli');
392 $rpcenv->init_request();
393 $rpcenv->set_language($ENV{LANG});
394 $rpcenv->set_user('root@pam');
395 }
93ddd7bc 396
7fe1f565
DM
397 no strict 'refs';
398 my $def = ${"${class}::cmddef"};
93ddd7bc 399
7fe1f565
DM
400 if (ref($def) eq 'ARRAY') {
401 handle_simple_cmd($def, \@ARGV, $pwcallback, $podfn, $preparefunc);
402 } else {
403 $cmddef = $def;
404 my $cmd = shift @ARGV;
405 handle_cmd($cmddef, $exename, $cmd, \@ARGV, $pwcallback, $podfn, $preparefunc);
406 }
93ddd7bc
DM
407
408 exit 0;
409}
410
e143e9d8 411sub handle_cmd {
8e3e9929 412 my ($def, $cmdname, $cmd, $args, $pwcallback, $podfn, $preparefunc) = @_;
e143e9d8
DM
413
414 $cmddef = $def;
415 $exename = $cmdname;
416
417 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
418
419 if (!$cmd) {
420 print_usage_short (\*STDERR, "no command specified");
421 exit (-1);
422 } elsif ($cmd eq 'verifyapi') {
423 PVE::RESTHandler::validate_method_schemas();
424 return;
425 } elsif ($cmd eq 'printmanpod') {
edf3d572 426 $podfn = find_cli_class_source($exename) if !defined($podfn);
e143e9d8
DM
427 print_pod_manpage($podfn);
428 return;
d8053c08
DM
429 } elsif ($cmd eq 'bashcomplete') {
430 &$print_bash_completion($cmddef, 0, @$args);
431 return;
e143e9d8
DM
432 }
433
8e3e9929
WB
434 &$preparefunc() if $preparefunc;
435
e143e9d8
DM
436 $cmd = &$expand_command_name($cmddef, $cmd);
437
438 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef->{$cmd} || []};
439
440 if (!$class) {
441 print_usage_short (\*STDERR, "unknown command '$cmd'");
442 exit (-1);
443 }
444
445 my $prefix = "$exename $cmd";
446 my $res = $class->cli_handler($prefix, $name, \@ARGV, $arg_param, $uri_param, $pwcallback);
2026f4b5
DM
447
448 &$outsub($res) if $outsub;
449}
450
451sub handle_simple_cmd {
7fe1f565 452 my ($def, $args, $pwcallback, $podfn, $preparefunc) = @_;
2026f4b5
DM
453
454 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def};
455 die "no class specified" if !$class;
456
d8053c08 457 if (scalar(@$args) >= 1) {
2026f4b5
DM
458 if ($args->[0] eq 'help') {
459 my $str = "USAGE: $name help\n";
460 $str .= $class->usage_str($name, $name, $arg_param, $uri_param, 'long');
461 print STDERR "$str\n\n";
462 return;
d8053c08
DM
463 } elsif ($args->[0] eq 'bashcomplete') {
464 shift @$args;
465 &$print_bash_completion({ $name => $def }, $name, @$args);
466 return;
2026f4b5
DM
467 } elsif ($args->[0] eq 'verifyapi') {
468 PVE::RESTHandler::validate_method_schemas();
469 return;
470 } elsif ($args->[0] eq 'printmanpod') {
7fe1f565
DM
471 $podfn = find_cli_class_source($name) if !defined($podfn);
472 print_simple_pod_manpage($podfn, @$def);
2026f4b5
DM
473 return;
474 }
e143e9d8 475 }
2026f4b5 476
7fe1f565
DM
477 &$preparefunc() if $preparefunc;
478
2026f4b5
DM
479 my $res = $class->cli_handler($name, $name, \@ARGV, $arg_param, $uri_param, $pwcallback);
480
481 &$outsub($res) if $outsub;
e143e9d8
DM
482}
483
4841;