]> git.proxmox.com Git - pve-common.git/blob - src/PVE/CLIHandler.pm
c6f11f6d449da44cb37a5e738427e9e7c5323e26
[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 $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
37 my $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
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,
62 completion => $complete_command_names,
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 && $cli_handler_class);
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 my $pwcallback = $cli_handler_class->can('read_password');
99 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
100
101 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param,
102 $verbose ? 'full' : 'short', $pwcallback,
103 $stringfilemap);
104 if ($verbose) {
105 print "$str\n";
106 } else {
107 print "USAGE: $str\n";
108 }
109
110 return undef;
111
112 }});
113
114 sub print_simple_asciidoc_synopsis {
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');
120 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
121
122 my $synopsis = "*${name}* `help`\n\n";
123
124 $synopsis .= $class->usage_str($name, $name, $arg_param, $uri_param,
125 'asciidoc', $pwcallback, $stringfilemap);
126
127 return $synopsis;
128 }
129
130 sub print_asciidoc_synopsis {
131
132 die "not initialized" if !($cmddef && $exename && $cli_handler_class);
133
134 my $pwcallback = $cli_handler_class->can('read_password');
135 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
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,
145 $uri_param, 'asciidoc', $pwcallback,
146 $stringfilemap);
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
158 sub print_usage_verbose {
159
160 die "not initialized" if !($cmddef && $exename && $cli_handler_class);
161
162 my $pwcallback = $cli_handler_class->can('read_password');
163 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
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}};
169 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param,
170 'full', $pwcallback, $stringfilemap);
171 print "$str\n\n";
172 }
173 }
174
175 sub sorted_commands {
176 return sort { ($cmddef->{$a}->[0] cmp $cmddef->{$b}->[0]) || ($a cmp $b)} keys %$cmddef;
177 }
178
179 sub print_usage_short {
180 my ($fd, $msg) = @_;
181
182 die "not initialized" if !($cmddef && $exename && $cli_handler_class);
183
184 my $pwcallback = $cli_handler_class->can('read_password');
185 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
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}};
193 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param, 'short', $pwcallback, $stringfilemap);
194 print $fd "\n" if $oldclass && $oldclass ne $class;
195 print $fd " $str";
196 $oldclass = $class;
197 }
198 }
199
200 my $print_bash_completion = sub {
201 my ($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
212 my $args = PVE::Tools::split_args($cmdline);
213 my $pos = scalar(@$args) - 2;
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 }
234 $cmd = $args->[1];
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
248 $arg_param = [ $arg_param ] if !ref($arg_param);
249
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') {
266 my $res = $d->{completion}->($cmd, $pname, $cur, $args);
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
304 sub verify_api {
305 my ($class) = @_;
306
307 # simply verify all registered methods
308 PVE::RESTHandler::validate_method_schemas();
309 }
310
311 my $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
321 sub generate_bash_completions {
322 my ($class) = @_;
323
324 # generate bash completion config
325
326 $exename = &$get_exe_name($class);
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
334 COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
335
336 complete -o default -C '$exename bashcomplete' $exename
337 __EOD__
338 }
339
340 sub generate_asciidoc_synopsys {
341 my ($class) = @_;
342 $class->generate_asciidoc_synopsis();
343 };
344
345 sub generate_asciidoc_synopsis {
346 my ($class) = @_;
347
348 $cli_handler_class = $class;
349
350 $exename = &$get_exe_name($class);
351
352 no strict 'refs';
353 my $def = ${"${class}::cmddef"};
354 $cmddef = $def;
355
356 if (ref($def) eq 'ARRAY') {
357 print_simple_asciidoc_synopsis(@$def);
358 } else {
359 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
360
361 print_asciidoc_synopsis();
362 }
363 }
364
365 # overwrite this if you want to run/setup things early
366 sub setup_environment {
367 my ($class) = @_;
368
369 # do nothing by default
370 }
371
372 my $handle_cmd = sub {
373 my ($args, $pwcallback, $preparefunc, $stringfilemap) = @_;
374
375 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
376
377 # call verifyapi before setup_environment(), because we do not want to
378 # execute any real code in this case
379
380 my $cmd = shift @$args;
381 if (!$cmd) {
382 print_usage_short (\*STDERR, "no command specified");
383 exit (-1);
384 } elsif ($cmd eq 'verifyapi') {
385 PVE::RESTHandler::validate_method_schemas();
386 return;
387 }
388
389 $cli_handler_class->setup_environment();
390
391 if ($cmd eq 'bashcomplete') {
392 &$print_bash_completion(undef, @$args);
393 return;
394 }
395
396 &$preparefunc() if $preparefunc;
397
398 $cmd = &$expand_command_name($cmddef, $cmd);
399
400 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef->{$cmd} || []};
401
402 if (!$class) {
403 print_usage_short (\*STDERR, "unknown command '$cmd'");
404 exit (-1);
405 }
406
407 my $prefix = "$exename $cmd";
408 my $res = $class->cli_handler($prefix, $name, \@ARGV, $arg_param, $uri_param, $pwcallback, $stringfilemap);
409
410 &$outsub($res) if $outsub;
411 };
412
413 my $handle_simple_cmd = sub {
414 my ($args, $pwcallback, $preparefunc, $stringfilemap) = @_;
415
416 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef};
417 die "no class specified" if !$class;
418
419 if (scalar(@$args) >= 1) {
420 if ($args->[0] eq 'help') {
421 my $str = "USAGE: $name help\n";
422 $str .= $class->usage_str($name, $name, $arg_param, $uri_param, 'long', $pwcallback, $stringfilemap);
423 print STDERR "$str\n\n";
424 return;
425 } elsif ($args->[0] eq 'verifyapi') {
426 PVE::RESTHandler::validate_method_schemas();
427 return;
428 }
429 }
430
431 $cli_handler_class->setup_environment();
432
433 if (scalar(@$args) >= 1) {
434 if ($args->[0] eq 'bashcomplete') {
435 shift @$args;
436 &$print_bash_completion($name, @$args);
437 return;
438 }
439 }
440
441 &$preparefunc() if $preparefunc;
442
443 my $res = $class->cli_handler($name, $name, \@ARGV, $arg_param, $uri_param, $pwcallback, $stringfilemap);
444
445 &$outsub($res) if $outsub;
446 };
447
448 sub run_cli_handler {
449 my ($class, %params) = @_;
450
451 $cli_handler_class = $class;
452
453 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
454
455 foreach my $key (keys %params) {
456 next if $key eq 'prepare';
457 next if $key eq 'no_init'; # not used anymore
458 next if $key eq 'no_rpcenv'; # not used anymore
459 die "unknown parameter '$key'";
460 }
461
462 my $preparefunc = $params{prepare};
463
464 my $pwcallback = $class->can('read_password');
465 my $stringfilemap = $class->can('string_param_file_mapping');
466
467 $exename = &$get_exe_name($class);
468
469 initlog($exename);
470
471 no strict 'refs';
472 $cmddef = ${"${class}::cmddef"};
473
474 if (ref($cmddef) eq 'ARRAY') {
475 &$handle_simple_cmd(\@ARGV, $pwcallback, $preparefunc, $stringfilemap);
476 } else {
477 &$handle_cmd(\@ARGV, $pwcallback, $preparefunc, $stringfilemap);
478 }
479
480 exit 0;
481 }
482
483 1;