]> git.proxmox.com Git - pve-common.git/blob - src/PVE/CLIHandler.pm
f50611d257b6f8e6973a8dc84b33648578cb20f1
[pve-common.git] / src / PVE / CLIHandler.pm
1 package PVE::CLIHandler;
2
3 use strict;
4 use warnings;
5
6 use PVE::SafeSyslog;
7 use PVE::Exception qw(raise raise_param_exc);
8 use PVE::RESTHandler;
9 use PVE::INotify;
10
11 use base qw(PVE::RESTHandler);
12
13 my $cmddef;
14 my $exename;
15 my $cli_handler_class;
16
17 my $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
23 my $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
43 my $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
56 __PACKAGE__->register_method ({
57 name => 'help',
58 path => 'help',
59 method => 'GET',
60 description => "Get help about specified command.",
61 parameters => {
62 additionalProperties => 0,
63 properties => {
64 cmd => {
65 description => "Command name",
66 type => 'string',
67 optional => 1,
68 completion => $complete_command_names,
69 },
70 verbose => {
71 description => "Verbose output format.",
72 type => 'boolean',
73 optional => 1,
74 },
75 },
76 },
77 returns => { type => 'null' },
78
79 code => sub {
80 my ($param) = @_;
81
82 $assert_initialized->();
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();
92 } else {
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
104 my $pwcallback = $cli_handler_class->can('read_password');
105 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
106
107 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param,
108 $verbose ? 'full' : 'short', $pwcallback,
109 $stringfilemap);
110 if ($verbose) {
111 print "$str\n";
112 } else {
113 print "USAGE: $str\n";
114 }
115
116 return undef;
117
118 }});
119
120 sub print_simple_asciidoc_synopsis {
121 my ($class, $name, $arg_param, $uri_param) = @_;
122
123 $assert_initialized->();
124
125 my $pwcallback = $cli_handler_class->can('read_password');
126 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
127
128 my $synopsis = "*${name}* `help`\n\n";
129
130 $synopsis .= $class->usage_str($name, $name, $arg_param, $uri_param,
131 'asciidoc', $pwcallback, $stringfilemap);
132
133 return $synopsis;
134 }
135
136 sub print_asciidoc_synopsis {
137
138 $assert_initialized->();
139
140 my $pwcallback = $cli_handler_class->can('read_password');
141 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
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,
151 $uri_param, 'asciidoc', $pwcallback,
152 $stringfilemap);
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
164 sub print_usage_verbose {
165
166 $assert_initialized->();
167
168 my $pwcallback = $cli_handler_class->can('read_password');
169 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
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}};
175 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param,
176 'full', $pwcallback, $stringfilemap);
177 print "$str\n\n";
178 }
179 }
180
181 sub sorted_commands {
182 return sort { ($cmddef->{$a}->[0] cmp $cmddef->{$b}->[0]) || ($a cmp $b)} keys %$cmddef;
183 }
184
185 sub print_usage_short {
186 my ($fd, $msg) = @_;
187
188 $assert_initialized->();
189
190 my $pwcallback = $cli_handler_class->can('read_password');
191 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
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}};
199 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param, 'short', $pwcallback, $stringfilemap);
200 print $fd "\n" if $oldclass && $oldclass ne $class;
201 print $fd " $str";
202 $oldclass = $class;
203 }
204 }
205
206 my $print_bash_completion = sub {
207 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
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
218 my $args = PVE::Tools::split_args($cmdline);
219 my $pos = scalar(@$args) - 2;
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 }
240 $cmd = $args->[1];
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
254 $arg_param = [ $arg_param ] if !ref($arg_param);
255
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') {
272 my $res = $d->{completion}->($cmd, $pname, $cur, $args);
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
310 sub verify_api {
311 my ($class) = @_;
312
313 # simply verify all registered methods
314 PVE::RESTHandler::validate_method_schemas();
315 }
316
317 my $get_exe_name = sub {
318 my ($class) = @_;
319
320 my $name = $class;
321 $name =~ s/^.*:://;
322 $name =~ s/_/-/g;
323
324 return $name;
325 };
326
327 sub generate_bash_completions {
328 my ($class) = @_;
329
330 # generate bash completion config
331
332 $exename = &$get_exe_name($class);
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
340 COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
341
342 complete -o default -C '$exename bashcomplete' $exename
343 __EOD__
344 }
345
346 sub generate_asciidoc_synopsys {
347 my ($class) = @_;
348 $class->generate_asciidoc_synopsis();
349 };
350
351 sub generate_asciidoc_synopsis {
352 my ($class) = @_;
353
354 $cli_handler_class = $class;
355
356 $exename = &$get_exe_name($class);
357
358 no strict 'refs';
359 my $def = ${"${class}::cmddef"};
360 $cmddef = $def;
361
362 if (ref($def) eq 'ARRAY') {
363 print_simple_asciidoc_synopsis(@$def);
364 } else {
365 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
366
367 print_asciidoc_synopsis();
368 }
369 }
370
371 # overwrite this if you want to run/setup things early
372 sub setup_environment {
373 my ($class) = @_;
374
375 # do nothing by default
376 }
377
378 my $handle_cmd = sub {
379 my ($args, $pwcallback, $preparefunc, $stringfilemap) = @_;
380
381 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
382
383 # call verifyapi before setup_environment(), because we do not want to
384 # execute any real code in this case
385
386 my $cmd = shift @$args;
387 if (!$cmd) {
388 print_usage_short (\*STDERR, "no command specified");
389 exit (-1);
390 } elsif ($cmd eq 'verifyapi') {
391 PVE::RESTHandler::validate_method_schemas();
392 return;
393 }
394
395 $cli_handler_class->setup_environment();
396
397 if ($cmd eq 'bashcomplete') {
398 &$print_bash_completion(undef, @$args);
399 return;
400 }
401
402 &$preparefunc() if $preparefunc;
403
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";
414 my $res = $class->cli_handler($prefix, $name, \@ARGV, $arg_param, $uri_param, $pwcallback, $stringfilemap);
415
416 &$outsub($res) if $outsub;
417 };
418
419 my $handle_simple_cmd = sub {
420 my ($args, $pwcallback, $preparefunc, $stringfilemap) = @_;
421
422 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef};
423 die "no class specified" if !$class;
424
425 if (scalar(@$args) >= 1) {
426 if ($args->[0] eq 'help') {
427 my $str = "USAGE: $name help\n";
428 $str .= $class->usage_str($name, $name, $arg_param, $uri_param, 'long', $pwcallback, $stringfilemap);
429 print STDERR "$str\n\n";
430 return;
431 } elsif ($args->[0] eq 'verifyapi') {
432 PVE::RESTHandler::validate_method_schemas();
433 return;
434 }
435 }
436
437 $cli_handler_class->setup_environment();
438
439 if (scalar(@$args) >= 1) {
440 if ($args->[0] eq 'bashcomplete') {
441 shift @$args;
442 &$print_bash_completion($name, @$args);
443 return;
444 }
445 }
446
447 &$preparefunc() if $preparefunc;
448
449 my $res = $class->cli_handler($name, $name, \@ARGV, $arg_param, $uri_param, $pwcallback, $stringfilemap);
450
451 &$outsub($res) if $outsub;
452 };
453
454 sub run_cli_handler {
455 my ($class, %params) = @_;
456
457 $cli_handler_class = $class;
458
459 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
460
461 foreach my $key (keys %params) {
462 next if $key eq 'prepare';
463 next if $key eq 'no_init'; # not used anymore
464 next if $key eq 'no_rpcenv'; # not used anymore
465 die "unknown parameter '$key'";
466 }
467
468 my $preparefunc = $params{prepare};
469
470 my $pwcallback = $class->can('read_password');
471 my $stringfilemap = $class->can('string_param_file_mapping');
472
473 $exename = &$get_exe_name($class);
474
475 initlog($exename);
476
477 no strict 'refs';
478 $cmddef = ${"${class}::cmddef"};
479
480 if (ref($cmddef) eq 'ARRAY') {
481 &$handle_simple_cmd(\@ARGV, $pwcallback, $preparefunc, $stringfilemap);
482 } else {
483 &$handle_cmd(\@ARGV, $pwcallback, $preparefunc, $stringfilemap);
484 }
485
486 exit 0;
487 }
488
489 1;