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