]> git.proxmox.com Git - pve-common.git/blame - src/PVE/CLIHandler.pm
JSONSchema: add fingerprint-sha256 standard option
[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 16
d204696c
TL
17my $assert_initialized = sub {
18 my @caller = caller;
19 die "$caller[0]:$caller[2] - not initialized\n"
20 if !($cmddef && $exename && $cli_handler_class);
21};
22
918140af
TL
23my $abort = sub {
24 my ($reason, $cmd) = @_;
25 print_usage_short (\*STDERR, $reason, $cmd);
26 exit (-1);
27};
28
e143e9d8
DM
29my $expand_command_name = sub {
30 my ($def, $cmd) = @_;
31
32 if (!$def->{$cmd}) {
7bac844e
TL
33 my @expanded = grep { /^\Q$cmd\E/ } keys %$def;
34 return $expanded[0] if scalar(@expanded) == 1; # enforce exact match
e143e9d8
DM
35 }
36 return $cmd;
37};
38
edf3d572 39my $complete_command_names = sub {
7bac844e 40 return [ sort keys %$cmddef ];
edf3d572
DM
41};
42
e143e9d8 43__PACKAGE__->register_method ({
3ef20687 44 name => 'help',
e143e9d8
DM
45 path => 'help',
46 method => 'GET',
47 description => "Get help about specified command.",
48 parameters => {
3ef20687 49 additionalProperties => 0,
e143e9d8
DM
50 properties => {
51 cmd => {
52 description => "Command name",
53 type => 'string',
54 optional => 1,
edf3d572 55 completion => $complete_command_names,
e143e9d8
DM
56 },
57 verbose => {
58 description => "Verbose output format.",
59 type => 'boolean',
60 optional => 1,
61 },
62 },
63 },
64 returns => { type => 'null' },
3ef20687 65
e143e9d8
DM
66 code => sub {
67 my ($param) = @_;
68
d204696c 69 $assert_initialized->();
e143e9d8
DM
70
71 my $cmd = $param->{cmd};
72
73 my $verbose = defined($cmd) && $cmd;
74 $verbose = $param->{verbose} if defined($param->{verbose});
75
76 if (!$cmd) {
77 if ($verbose) {
78 print_usage_verbose();
3ef20687 79 } else {
e143e9d8
DM
80 print_usage_short(\*STDOUT);
81 }
82 return undef;
83 }
84
85 $cmd = &$expand_command_name($cmddef, $cmd);
86
87 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd} || []};
88
89 raise_param_exc({ cmd => "no such command '$cmd'"}) if !$class;
90
891b798d 91 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 92 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
e143e9d8 93
891b798d 94 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param,
4845032a
FG
95 $verbose ? 'full' : 'short', $pwcallback,
96 $stringfilemap);
e143e9d8
DM
97 if ($verbose) {
98 print "$str\n";
99 } else {
100 print "USAGE: $str\n";
101 }
102
103 return undef;
104
105 }});
106
0a5a1eee 107sub print_simple_asciidoc_synopsis {
fe3f1fde
DM
108 my ($class, $name, $arg_param, $uri_param) = @_;
109
d204696c 110 $assert_initialized->();
fe3f1fde
DM
111
112 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 113 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
fe3f1fde
DM
114
115 my $synopsis = "*${name}* `help`\n\n";
116
4845032a
FG
117 $synopsis .= $class->usage_str($name, $name, $arg_param, $uri_param,
118 'asciidoc', $pwcallback, $stringfilemap);
fe3f1fde
DM
119
120 return $synopsis;
121}
122
0a5a1eee 123sub print_asciidoc_synopsis {
fe3f1fde 124
d204696c 125 $assert_initialized->();
fe3f1fde
DM
126
127 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 128 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
fe3f1fde
DM
129
130 my $synopsis = "";
131
132 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
133
134 my $oldclass;
135 foreach my $cmd (sort keys %$cmddef) {
136 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd}};
137 my $str = $class->usage_str($name, "$exename $cmd", $arg_param,
4845032a
FG
138 $uri_param, 'asciidoc', $pwcallback,
139 $stringfilemap);
fe3f1fde
DM
140 $synopsis .= "\n" if $oldclass && $oldclass ne $class;
141
142 $synopsis .= "$str\n\n";
143 $oldclass = $class;
144 }
145
146 $synopsis .= "\n";
147
148 return $synopsis;
149}
150
e143e9d8
DM
151sub print_usage_verbose {
152
d204696c 153 $assert_initialized->();
891b798d
DM
154
155 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 156 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
e143e9d8
DM
157
158 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
159
160 foreach my $cmd (sort keys %$cmddef) {
161 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd}};
891b798d 162 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param,
4845032a 163 'full', $pwcallback, $stringfilemap);
e143e9d8
DM
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
d204696c 175 $assert_initialized->();
891b798d
DM
176
177 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 178 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
e143e9d8
DM
179
180 print $fd "ERROR: $msg\n" if $msg;
181 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
182
183 my $oldclass;
184 foreach my $cmd (sorted_commands()) {
185 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd}};
4845032a 186 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param, 'short', $pwcallback, $stringfilemap);
e143e9d8
DM
187 print $fd "\n" if $oldclass && $oldclass ne $class;
188 print $fd " $str";
189 $oldclass = $class;
190 }
191}
192
d8053c08 193my $print_bash_completion = sub {
57e67ea3 194 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
d8053c08
DM
195
196 my $debug = 0;
197
198 return if !(defined($cur) && defined($prev) && defined($bash_command));
199 return if !defined($ENV{COMP_LINE});
200 return if !defined($ENV{COMP_POINT});
201
202 my $cmdline = substr($ENV{COMP_LINE}, 0, $ENV{COMP_POINT});
203 print STDERR "\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
204
58d9e664
DM
205 my $args = PVE::Tools::split_args($cmdline);
206 my $pos = scalar(@$args) - 2;
d8053c08
DM
207 $pos += 1 if $cmdline =~ m/\s+$/;
208
209 print STDERR "CMDLINE:$pos:$cmdline\n" if $debug;
210
211 return if $pos < 0;
212
213 my $print_result = sub {
214 foreach my $p (@_) {
215 print "$p\n" if $p =~ m/^$cur/;
216 }
217 };
218
219 my $cmd;
220 if ($simple_cmd) {
221 $cmd = $simple_cmd;
222 } else {
223 if ($pos == 0) {
224 &$print_result(keys %$cmddef);
225 return;
226 }
58d9e664 227 $cmd = $args->[1];
d8053c08
DM
228 }
229
230 my $def = $cmddef->{$cmd};
231 return if !$def;
232
233 print STDERR "CMDLINE1:$pos:$cmdline\n" if $debug;
234
235 my $skip_param = {};
236
237 my ($class, $name, $arg_param, $uri_param) = @$def;
238 $arg_param //= [];
239 $uri_param //= {};
240
d90a2fd0
DM
241 $arg_param = [ $arg_param ] if !ref($arg_param);
242
d8053c08
DM
243 map { $skip_param->{$_} = 1; } @$arg_param;
244 map { $skip_param->{$_} = 1; } keys %$uri_param;
245
246 my $fpcount = scalar(@$arg_param);
247
248 my $info = $class->map_method_by_name($name);
249
250 my $schema = $info->{parameters};
251 my $prop = $schema->{properties};
252
253 my $print_parameter_completion = sub {
254 my ($pname) = @_;
255 my $d = $prop->{$pname};
256 if ($d->{completion}) {
257 my $vt = ref($d->{completion});
258 if ($vt eq 'CODE') {
58d9e664 259 my $res = $d->{completion}->($cmd, $pname, $cur, $args);
d8053c08
DM
260 &$print_result(@$res);
261 }
262 } elsif ($d->{type} eq 'boolean') {
263 &$print_result('0', '1');
264 } elsif ($d->{enum}) {
265 &$print_result(@{$d->{enum}});
266 }
267 };
268
269 # positional arguments
270 $pos += 1 if $simple_cmd;
271 if ($fpcount && $pos <= $fpcount) {
272 my $pname = $arg_param->[$pos -1];
273 &$print_parameter_completion($pname);
274 return;
275 }
276
277 my @option_list = ();
278 foreach my $key (keys %$prop) {
279 next if $skip_param->{$key};
280 push @option_list, "--$key";
281 }
282
283 if ($cur =~ m/^-/) {
284 &$print_result(@option_list);
285 return;
286 }
287
288 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
289 my $pname = $1;
290 &$print_parameter_completion($pname);
291 return;
292 }
293
294 &$print_result(@option_list);
295};
296
1f130ba6
DM
297sub verify_api {
298 my ($class) = @_;
299
300 # simply verify all registered methods
301 PVE::RESTHandler::validate_method_schemas();
302}
303
8f3712f8
DM
304my $get_exe_name = sub {
305 my ($class) = @_;
3ef20687 306
8f3712f8
DM
307 my $name = $class;
308 $name =~ s/^.*:://;
309 $name =~ s/_/-/g;
310
311 return $name;
312};
313
c45707a0
DM
314sub generate_bash_completions {
315 my ($class) = @_;
316
317 # generate bash completion config
318
8f3712f8 319 $exename = &$get_exe_name($class);
c45707a0
DM
320
321 print <<__EOD__;
322# $exename bash completion
323
324# see http://tiswww.case.edu/php/chet/bash/FAQ
325# and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
326# this modifies global var, but I found no better way
327COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
328
e4a1d8e2 329complete -o default -C '$exename bashcomplete' $exename
c45707a0
DM
330__EOD__
331}
332
fe3f1fde
DM
333sub generate_asciidoc_synopsys {
334 my ($class) = @_;
0a5a1eee
FG
335 $class->generate_asciidoc_synopsis();
336};
337
338sub generate_asciidoc_synopsis {
339 my ($class) = @_;
fe3f1fde
DM
340
341 $cli_handler_class = $class;
342
343 $exename = &$get_exe_name($class);
344
345 no strict 'refs';
346 my $def = ${"${class}::cmddef"};
57e67ea3 347 $cmddef = $def;
fe3f1fde
DM
348
349 if (ref($def) eq 'ARRAY') {
0a5a1eee 350 print_simple_asciidoc_synopsis(@$def);
fe3f1fde 351 } else {
fe3f1fde
DM
352 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
353
0a5a1eee 354 print_asciidoc_synopsis();
fe3f1fde
DM
355 }
356}
357
7b7f99c9
DM
358# overwrite this if you want to run/setup things early
359sub setup_environment {
360 my ($class) = @_;
361
362 # do nothing by default
363}
364
891b798d 365my $handle_cmd = sub {
57e67ea3 366 my ($args, $pwcallback, $preparefunc, $stringfilemap) = @_;
e143e9d8
DM
367
368 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
369
7b7f99c9 370
57e67ea3 371 my $cmd = shift @$args;
918140af
TL
372 $abort->("no command specified") if !$cmd;
373
374 # call verifyapi before setup_environment(), don't execute any real code in
375 # this case
376 if ($cmd eq 'verifyapi') {
e143e9d8
DM
377 PVE::RESTHandler::validate_method_schemas();
378 return;
7b7f99c9
DM
379 }
380
381 $cli_handler_class->setup_environment();
382
383 if ($cmd eq 'bashcomplete') {
57e67ea3 384 &$print_bash_completion(undef, @$args);
d8053c08 385 return;
e143e9d8
DM
386 }
387
8e3e9929
WB
388 &$preparefunc() if $preparefunc;
389
e143e9d8
DM
390 $cmd = &$expand_command_name($cmddef, $cmd);
391
392 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef->{$cmd} || []};
918140af 393 $abort->("unknown command '$cmd'") if !$class;
e143e9d8
DM
394
395 my $prefix = "$exename $cmd";
408976c6 396 my $res = $class->cli_handler($prefix, $name, \@ARGV, $arg_param, $uri_param, $pwcallback, $stringfilemap);
2026f4b5
DM
397
398 &$outsub($res) if $outsub;
891b798d 399};
2026f4b5 400
891b798d 401my $handle_simple_cmd = sub {
57e67ea3 402 my ($args, $pwcallback, $preparefunc, $stringfilemap) = @_;
2026f4b5 403
57e67ea3 404 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef};
2026f4b5
DM
405 die "no class specified" if !$class;
406
d8053c08 407 if (scalar(@$args) >= 1) {
2026f4b5
DM
408 if ($args->[0] eq 'help') {
409 my $str = "USAGE: $name help\n";
4845032a 410 $str .= $class->usage_str($name, $name, $arg_param, $uri_param, 'long', $pwcallback, $stringfilemap);
2026f4b5
DM
411 print STDERR "$str\n\n";
412 return;
413 } elsif ($args->[0] eq 'verifyapi') {
414 PVE::RESTHandler::validate_method_schemas();
415 return;
2026f4b5 416 }
e143e9d8 417 }
2026f4b5 418
7b7f99c9
DM
419 $cli_handler_class->setup_environment();
420
421 if (scalar(@$args) >= 1) {
422 if ($args->[0] eq 'bashcomplete') {
423 shift @$args;
57e67ea3 424 &$print_bash_completion($name, @$args);
7b7f99c9
DM
425 return;
426 }
427 }
428
7fe1f565
DM
429 &$preparefunc() if $preparefunc;
430
408976c6 431 my $res = $class->cli_handler($name, $name, \@ARGV, $arg_param, $uri_param, $pwcallback, $stringfilemap);
2026f4b5
DM
432
433 &$outsub($res) if $outsub;
891b798d
DM
434};
435
891b798d
DM
436sub run_cli_handler {
437 my ($class, %params) = @_;
438
439 $cli_handler_class = $class;
440
441 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
442
aa9b9af5 443 foreach my $key (keys %params) {
5ae87c41 444 next if $key eq 'prepare';
1042b82c
DM
445 next if $key eq 'no_init'; # not used anymore
446 next if $key eq 'no_rpcenv'; # not used anymore
aa9b9af5
DM
447 die "unknown parameter '$key'";
448 }
449
5ae87c41 450 my $preparefunc = $params{prepare};
891b798d
DM
451
452 my $pwcallback = $class->can('read_password');
408976c6 453 my $stringfilemap = $class->can('string_param_file_mapping');
891b798d
DM
454
455 $exename = &$get_exe_name($class);
456
457 initlog($exename);
458
891b798d 459 no strict 'refs';
57e67ea3 460 $cmddef = ${"${class}::cmddef"};
891b798d 461
57e67ea3
TL
462 if (ref($cmddef) eq 'ARRAY') {
463 &$handle_simple_cmd(\@ARGV, $pwcallback, $preparefunc, $stringfilemap);
891b798d 464 } else {
57e67ea3 465 &$handle_cmd(\@ARGV, $pwcallback, $preparefunc, $stringfilemap);
891b798d
DM
466 }
467
468 exit 0;
e143e9d8
DM
469}
470
4711;