]> git.proxmox.com Git - pve-common.git/blame - src/PVE/CLIHandler.pm
cli: code cleanup
[pve-common.git] / src / PVE / CLIHandler.pm
CommitLineData
e143e9d8
DM
1package PVE::CLIHandler;
2
3use strict;
4use warnings;
5
93ddd7bc 6use PVE::SafeSyslog;
e143e9d8
DM
7use PVE::Exception qw(raise raise_param_exc);
8use PVE::RESTHandler;
881eb755 9use PVE::INotify;
e143e9d8
DM
10
11use base qw(PVE::RESTHandler);
12
13my $cmddef;
14my $exename;
891b798d 15my $cli_handler_class;
e143e9d8
DM
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
891b798d 76 die "not initialized" if !($cmddef && $exename && $cli_handler_class);
e143e9d8
DM
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
891b798d 98 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 99 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
e143e9d8 100
891b798d 101 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param,
4845032a
FG
102 $verbose ? 'full' : 'short', $pwcallback,
103 $stringfilemap);
e143e9d8
DM
104 if ($verbose) {
105 print "$str\n";
106 } else {
107 print "USAGE: $str\n";
108 }
109
110 return undef;
111
112 }});
113
0a5a1eee 114sub print_simple_asciidoc_synopsis {
fe3f1fde
DM
115 my ($class, $name, $arg_param, $uri_param) = @_;
116
117 die "not initialized" if !$cli_handler_class;
118
119 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 120 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
fe3f1fde
DM
121
122 my $synopsis = "*${name}* `help`\n\n";
123
4845032a
FG
124 $synopsis .= $class->usage_str($name, $name, $arg_param, $uri_param,
125 'asciidoc', $pwcallback, $stringfilemap);
fe3f1fde
DM
126
127 return $synopsis;
128}
129
0a5a1eee 130sub print_asciidoc_synopsis {
fe3f1fde
DM
131
132 die "not initialized" if !($cmddef && $exename && $cli_handler_class);
133
134 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 135 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
fe3f1fde
DM
136
137 my $synopsis = "";
138
139 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
140
141 my $oldclass;
142 foreach my $cmd (sort keys %$cmddef) {
143 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd}};
144 my $str = $class->usage_str($name, "$exename $cmd", $arg_param,
4845032a
FG
145 $uri_param, 'asciidoc', $pwcallback,
146 $stringfilemap);
fe3f1fde
DM
147 $synopsis .= "\n" if $oldclass && $oldclass ne $class;
148
149 $synopsis .= "$str\n\n";
150 $oldclass = $class;
151 }
152
153 $synopsis .= "\n";
154
155 return $synopsis;
156}
157
e143e9d8
DM
158sub print_usage_verbose {
159
891b798d
DM
160 die "not initialized" if !($cmddef && $exename && $cli_handler_class);
161
162 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 163 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
e143e9d8
DM
164
165 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
166
167 foreach my $cmd (sort keys %$cmddef) {
168 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd}};
891b798d 169 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param,
4845032a 170 'full', $pwcallback, $stringfilemap);
e143e9d8
DM
171 print "$str\n\n";
172 }
173}
174
175sub sorted_commands {
176 return sort { ($cmddef->{$a}->[0] cmp $cmddef->{$b}->[0]) || ($a cmp $b)} keys %$cmddef;
177}
178
179sub print_usage_short {
180 my ($fd, $msg) = @_;
181
891b798d
DM
182 die "not initialized" if !($cmddef && $exename && $cli_handler_class);
183
184 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 185 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
e143e9d8
DM
186
187 print $fd "ERROR: $msg\n" if $msg;
188 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
189
190 my $oldclass;
191 foreach my $cmd (sorted_commands()) {
192 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd}};
4845032a 193 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param, 'short', $pwcallback, $stringfilemap);
e143e9d8
DM
194 print $fd "\n" if $oldclass && $oldclass ne $class;
195 print $fd " $str";
196 $oldclass = $class;
197 }
198}
199
d8053c08
DM
200my $print_bash_completion = sub {
201 my ($cmddef, $simple_cmd, $bash_command, $cur, $prev) = @_;
202
203 my $debug = 0;
204
205 return if !(defined($cur) && defined($prev) && defined($bash_command));
206 return if !defined($ENV{COMP_LINE});
207 return if !defined($ENV{COMP_POINT});
208
209 my $cmdline = substr($ENV{COMP_LINE}, 0, $ENV{COMP_POINT});
210 print STDERR "\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
211
58d9e664
DM
212 my $args = PVE::Tools::split_args($cmdline);
213 my $pos = scalar(@$args) - 2;
d8053c08
DM
214 $pos += 1 if $cmdline =~ m/\s+$/;
215
216 print STDERR "CMDLINE:$pos:$cmdline\n" if $debug;
217
218 return if $pos < 0;
219
220 my $print_result = sub {
221 foreach my $p (@_) {
222 print "$p\n" if $p =~ m/^$cur/;
223 }
224 };
225
226 my $cmd;
227 if ($simple_cmd) {
228 $cmd = $simple_cmd;
229 } else {
230 if ($pos == 0) {
231 &$print_result(keys %$cmddef);
232 return;
233 }
58d9e664 234 $cmd = $args->[1];
d8053c08
DM
235 }
236
237 my $def = $cmddef->{$cmd};
238 return if !$def;
239
240 print STDERR "CMDLINE1:$pos:$cmdline\n" if $debug;
241
242 my $skip_param = {};
243
244 my ($class, $name, $arg_param, $uri_param) = @$def;
245 $arg_param //= [];
246 $uri_param //= {};
247
d90a2fd0
DM
248 $arg_param = [ $arg_param ] if !ref($arg_param);
249
d8053c08
DM
250 map { $skip_param->{$_} = 1; } @$arg_param;
251 map { $skip_param->{$_} = 1; } keys %$uri_param;
252
253 my $fpcount = scalar(@$arg_param);
254
255 my $info = $class->map_method_by_name($name);
256
257 my $schema = $info->{parameters};
258 my $prop = $schema->{properties};
259
260 my $print_parameter_completion = sub {
261 my ($pname) = @_;
262 my $d = $prop->{$pname};
263 if ($d->{completion}) {
264 my $vt = ref($d->{completion});
265 if ($vt eq 'CODE') {
58d9e664 266 my $res = $d->{completion}->($cmd, $pname, $cur, $args);
d8053c08
DM
267 &$print_result(@$res);
268 }
269 } elsif ($d->{type} eq 'boolean') {
270 &$print_result('0', '1');
271 } elsif ($d->{enum}) {
272 &$print_result(@{$d->{enum}});
273 }
274 };
275
276 # positional arguments
277 $pos += 1 if $simple_cmd;
278 if ($fpcount && $pos <= $fpcount) {
279 my $pname = $arg_param->[$pos -1];
280 &$print_parameter_completion($pname);
281 return;
282 }
283
284 my @option_list = ();
285 foreach my $key (keys %$prop) {
286 next if $skip_param->{$key};
287 push @option_list, "--$key";
288 }
289
290 if ($cur =~ m/^-/) {
291 &$print_result(@option_list);
292 return;
293 }
294
295 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
296 my $pname = $1;
297 &$print_parameter_completion($pname);
298 return;
299 }
300
301 &$print_result(@option_list);
302};
303
1f130ba6
DM
304sub verify_api {
305 my ($class) = @_;
306
307 # simply verify all registered methods
308 PVE::RESTHandler::validate_method_schemas();
309}
310
8f3712f8
DM
311my $get_exe_name = sub {
312 my ($class) = @_;
313
314 my $name = $class;
315 $name =~ s/^.*:://;
316 $name =~ s/_/-/g;
317
318 return $name;
319};
320
c45707a0
DM
321sub generate_bash_completions {
322 my ($class) = @_;
323
324 # generate bash completion config
325
8f3712f8 326 $exename = &$get_exe_name($class);
c45707a0
DM
327
328 print <<__EOD__;
329# $exename bash completion
330
331# see http://tiswww.case.edu/php/chet/bash/FAQ
332# and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
333# this modifies global var, but I found no better way
334COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
335
e4a1d8e2 336complete -o default -C '$exename bashcomplete' $exename
c45707a0
DM
337__EOD__
338}
339
fe3f1fde
DM
340sub generate_asciidoc_synopsys {
341 my ($class) = @_;
0a5a1eee
FG
342 $class->generate_asciidoc_synopsis();
343};
344
345sub generate_asciidoc_synopsis {
346 my ($class) = @_;
fe3f1fde
DM
347
348 $cli_handler_class = $class;
349
350 $exename = &$get_exe_name($class);
351
352 no strict 'refs';
353 my $def = ${"${class}::cmddef"};
354
355 if (ref($def) eq 'ARRAY') {
0a5a1eee 356 print_simple_asciidoc_synopsis(@$def);
fe3f1fde
DM
357 } else {
358 $cmddef = $def;
359
360 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
361
0a5a1eee 362 print_asciidoc_synopsis();
fe3f1fde
DM
363 }
364}
365
7b7f99c9
DM
366# overwrite this if you want to run/setup things early
367sub setup_environment {
368 my ($class) = @_;
369
370 # do nothing by default
371}
372
891b798d 373my $handle_cmd = sub {
bf27456b 374 my ($def, $cmdname, $cmd, $args, $pwcallback, $preparefunc, $stringfilemap) = @_;
e143e9d8
DM
375
376 $cmddef = $def;
377 $exename = $cmdname;
378
379 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
380
7b7f99c9
DM
381 # call verifyapi before setup_environment(), because we do not want to
382 # execute any real code in this case
383
384 if (!$cmd) {
e143e9d8
DM
385 print_usage_short (\*STDERR, "no command specified");
386 exit (-1);
387 } elsif ($cmd eq 'verifyapi') {
388 PVE::RESTHandler::validate_method_schemas();
389 return;
7b7f99c9
DM
390 }
391
392 $cli_handler_class->setup_environment();
393
394 if ($cmd eq 'bashcomplete') {
d8053c08
DM
395 &$print_bash_completion($cmddef, 0, @$args);
396 return;
e143e9d8
DM
397 }
398
8e3e9929
WB
399 &$preparefunc() if $preparefunc;
400
e143e9d8
DM
401 $cmd = &$expand_command_name($cmddef, $cmd);
402
403 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef->{$cmd} || []};
404
405 if (!$class) {
406 print_usage_short (\*STDERR, "unknown command '$cmd'");
407 exit (-1);
408 }
409
410 my $prefix = "$exename $cmd";
408976c6 411 my $res = $class->cli_handler($prefix, $name, \@ARGV, $arg_param, $uri_param, $pwcallback, $stringfilemap);
2026f4b5
DM
412
413 &$outsub($res) if $outsub;
891b798d 414};
2026f4b5 415
891b798d 416my $handle_simple_cmd = sub {
bf27456b 417 my ($def, $args, $pwcallback, $preparefunc, $stringfilemap) = @_;
2026f4b5
DM
418
419 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def};
420 die "no class specified" if !$class;
421
d8053c08 422 if (scalar(@$args) >= 1) {
2026f4b5
DM
423 if ($args->[0] eq 'help') {
424 my $str = "USAGE: $name help\n";
4845032a 425 $str .= $class->usage_str($name, $name, $arg_param, $uri_param, 'long', $pwcallback, $stringfilemap);
2026f4b5
DM
426 print STDERR "$str\n\n";
427 return;
428 } elsif ($args->[0] eq 'verifyapi') {
429 PVE::RESTHandler::validate_method_schemas();
430 return;
2026f4b5 431 }
e143e9d8 432 }
2026f4b5 433
7b7f99c9
DM
434 $cli_handler_class->setup_environment();
435
436 if (scalar(@$args) >= 1) {
437 if ($args->[0] eq 'bashcomplete') {
438 shift @$args;
439 &$print_bash_completion({ $name => $def }, $name, @$args);
440 return;
441 }
442 }
443
7fe1f565
DM
444 &$preparefunc() if $preparefunc;
445
408976c6 446 my $res = $class->cli_handler($name, $name, \@ARGV, $arg_param, $uri_param, $pwcallback, $stringfilemap);
2026f4b5
DM
447
448 &$outsub($res) if $outsub;
891b798d
DM
449};
450
451sub run_cli {
452 my ($class, $pwcallback, $podfn, $preparefunc) = @_;
453
b7ef63ab
DM
454 # Note: "depreciated function run_cli - use run_cli_handler instead";
455 # silently ignore $podfn , which is no longer supported.
456
457 die "password callback is no longer supported" if $pwcallback;
458
459 run_cli_handler($class, prepare => $preparefunc);
891b798d
DM
460}
461
462sub run_cli_handler {
463 my ($class, %params) = @_;
464
465 $cli_handler_class = $class;
466
467 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
468
aa9b9af5 469 foreach my $key (keys %params) {
5ae87c41 470 next if $key eq 'prepare';
1042b82c
DM
471 next if $key eq 'no_init'; # not used anymore
472 next if $key eq 'no_rpcenv'; # not used anymore
aa9b9af5
DM
473 die "unknown parameter '$key'";
474 }
475
5ae87c41 476 my $preparefunc = $params{prepare};
891b798d
DM
477
478 my $pwcallback = $class->can('read_password');
408976c6 479 my $stringfilemap = $class->can('string_param_file_mapping');
891b798d
DM
480
481 $exename = &$get_exe_name($class);
482
483 initlog($exename);
484
891b798d
DM
485 no strict 'refs';
486 my $def = ${"${class}::cmddef"};
487
488 if (ref($def) eq 'ARRAY') {
bf27456b 489 &$handle_simple_cmd($def, \@ARGV, $pwcallback, $preparefunc, $stringfilemap);
891b798d
DM
490 } else {
491 $cmddef = $def;
492 my $cmd = shift @ARGV;
bf27456b 493 &$handle_cmd($cmddef, $exename, $cmd, \@ARGV, $pwcallback, $preparefunc, $stringfilemap);
891b798d
DM
494 }
495
496 exit 0;
e143e9d8
DM
497}
498
4991;