]> git.proxmox.com Git - pve-common.git/blob - src/PVE/CLIHandler.pm
cli: factor out abort
[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 $abort = sub {
24 my ($reason, $cmd) = @_;
25 print_usage_short (\*STDERR, $reason, $cmd);
26 exit (-1);
27 };
28
29 my $expand_command_name = sub {
30 my ($def, $cmd) = @_;
31
32 if (!$def->{$cmd}) {
33 my @expanded = grep { /^\Q$cmd\E/ } keys %$def;
34 return $expanded[0] if scalar(@expanded) == 1; # enforce exact match
35 }
36 return $cmd;
37 };
38
39 my $complete_command_names = sub {
40 return [ sort keys %$cmddef ];
41 };
42
43 __PACKAGE__->register_method ({
44 name => 'help',
45 path => 'help',
46 method => 'GET',
47 description => "Get help about specified command.",
48 parameters => {
49 additionalProperties => 0,
50 properties => {
51 cmd => {
52 description => "Command name",
53 type => 'string',
54 optional => 1,
55 completion => $complete_command_names,
56 },
57 verbose => {
58 description => "Verbose output format.",
59 type => 'boolean',
60 optional => 1,
61 },
62 },
63 },
64 returns => { type => 'null' },
65
66 code => sub {
67 my ($param) = @_;
68
69 $assert_initialized->();
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();
79 } else {
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
91 my $pwcallback = $cli_handler_class->can('read_password');
92 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
93
94 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param,
95 $verbose ? 'full' : 'short', $pwcallback,
96 $stringfilemap);
97 if ($verbose) {
98 print "$str\n";
99 } else {
100 print "USAGE: $str\n";
101 }
102
103 return undef;
104
105 }});
106
107 sub print_simple_asciidoc_synopsis {
108 my ($class, $name, $arg_param, $uri_param) = @_;
109
110 $assert_initialized->();
111
112 my $pwcallback = $cli_handler_class->can('read_password');
113 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
114
115 my $synopsis = "*${name}* `help`\n\n";
116
117 $synopsis .= $class->usage_str($name, $name, $arg_param, $uri_param,
118 'asciidoc', $pwcallback, $stringfilemap);
119
120 return $synopsis;
121 }
122
123 sub print_asciidoc_synopsis {
124
125 $assert_initialized->();
126
127 my $pwcallback = $cli_handler_class->can('read_password');
128 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
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,
138 $uri_param, 'asciidoc', $pwcallback,
139 $stringfilemap);
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
151 sub print_usage_verbose {
152
153 $assert_initialized->();
154
155 my $pwcallback = $cli_handler_class->can('read_password');
156 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
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}};
162 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param,
163 'full', $pwcallback, $stringfilemap);
164 print "$str\n\n";
165 }
166 }
167
168 sub sorted_commands {
169 return sort { ($cmddef->{$a}->[0] cmp $cmddef->{$b}->[0]) || ($a cmp $b)} keys %$cmddef;
170 }
171
172 sub print_usage_short {
173 my ($fd, $msg) = @_;
174
175 $assert_initialized->();
176
177 my $pwcallback = $cli_handler_class->can('read_password');
178 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
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}};
186 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param, 'short', $pwcallback, $stringfilemap);
187 print $fd "\n" if $oldclass && $oldclass ne $class;
188 print $fd " $str";
189 $oldclass = $class;
190 }
191 }
192
193 my $print_bash_completion = sub {
194 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
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
205 my $args = PVE::Tools::split_args($cmdline);
206 my $pos = scalar(@$args) - 2;
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 }
227 $cmd = $args->[1];
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
241 $arg_param = [ $arg_param ] if !ref($arg_param);
242
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') {
259 my $res = $d->{completion}->($cmd, $pname, $cur, $args);
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
297 sub verify_api {
298 my ($class) = @_;
299
300 # simply verify all registered methods
301 PVE::RESTHandler::validate_method_schemas();
302 }
303
304 my $get_exe_name = sub {
305 my ($class) = @_;
306
307 my $name = $class;
308 $name =~ s/^.*:://;
309 $name =~ s/_/-/g;
310
311 return $name;
312 };
313
314 sub generate_bash_completions {
315 my ($class) = @_;
316
317 # generate bash completion config
318
319 $exename = &$get_exe_name($class);
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
327 COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
328
329 complete -o default -C '$exename bashcomplete' $exename
330 __EOD__
331 }
332
333 sub generate_asciidoc_synopsys {
334 my ($class) = @_;
335 $class->generate_asciidoc_synopsis();
336 };
337
338 sub generate_asciidoc_synopsis {
339 my ($class) = @_;
340
341 $cli_handler_class = $class;
342
343 $exename = &$get_exe_name($class);
344
345 no strict 'refs';
346 my $def = ${"${class}::cmddef"};
347 $cmddef = $def;
348
349 if (ref($def) eq 'ARRAY') {
350 print_simple_asciidoc_synopsis(@$def);
351 } else {
352 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
353
354 print_asciidoc_synopsis();
355 }
356 }
357
358 # overwrite this if you want to run/setup things early
359 sub setup_environment {
360 my ($class) = @_;
361
362 # do nothing by default
363 }
364
365 my $handle_cmd = sub {
366 my ($args, $pwcallback, $preparefunc, $stringfilemap) = @_;
367
368 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
369
370
371 my $cmd = shift @$args;
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') {
377 PVE::RESTHandler::validate_method_schemas();
378 return;
379 }
380
381 $cli_handler_class->setup_environment();
382
383 if ($cmd eq 'bashcomplete') {
384 &$print_bash_completion(undef, @$args);
385 return;
386 }
387
388 &$preparefunc() if $preparefunc;
389
390 $cmd = &$expand_command_name($cmddef, $cmd);
391
392 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef->{$cmd} || []};
393 $abort->("unknown command '$cmd'") if !$class;
394
395 my $prefix = "$exename $cmd";
396 my $res = $class->cli_handler($prefix, $name, \@ARGV, $arg_param, $uri_param, $pwcallback, $stringfilemap);
397
398 &$outsub($res) if $outsub;
399 };
400
401 my $handle_simple_cmd = sub {
402 my ($args, $pwcallback, $preparefunc, $stringfilemap) = @_;
403
404 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef};
405 die "no class specified" if !$class;
406
407 if (scalar(@$args) >= 1) {
408 if ($args->[0] eq 'help') {
409 my $str = "USAGE: $name help\n";
410 $str .= $class->usage_str($name, $name, $arg_param, $uri_param, 'long', $pwcallback, $stringfilemap);
411 print STDERR "$str\n\n";
412 return;
413 } elsif ($args->[0] eq 'verifyapi') {
414 PVE::RESTHandler::validate_method_schemas();
415 return;
416 }
417 }
418
419 $cli_handler_class->setup_environment();
420
421 if (scalar(@$args) >= 1) {
422 if ($args->[0] eq 'bashcomplete') {
423 shift @$args;
424 &$print_bash_completion($name, @$args);
425 return;
426 }
427 }
428
429 &$preparefunc() if $preparefunc;
430
431 my $res = $class->cli_handler($name, $name, \@ARGV, $arg_param, $uri_param, $pwcallback, $stringfilemap);
432
433 &$outsub($res) if $outsub;
434 };
435
436 sub run_cli_handler {
437 my ($class, %params) = @_;
438
439 $cli_handler_class = $class;
440
441 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
442
443 foreach my $key (keys %params) {
444 next if $key eq 'prepare';
445 next if $key eq 'no_init'; # not used anymore
446 next if $key eq 'no_rpcenv'; # not used anymore
447 die "unknown parameter '$key'";
448 }
449
450 my $preparefunc = $params{prepare};
451
452 my $pwcallback = $class->can('read_password');
453 my $stringfilemap = $class->can('string_param_file_mapping');
454
455 $exename = &$get_exe_name($class);
456
457 initlog($exename);
458
459 no strict 'refs';
460 $cmddef = ${"${class}::cmddef"};
461
462 if (ref($cmddef) eq 'ARRAY') {
463 &$handle_simple_cmd(\@ARGV, $pwcallback, $preparefunc, $stringfilemap);
464 } else {
465 &$handle_cmd(\@ARGV, $pwcallback, $preparefunc, $stringfilemap);
466 }
467
468 exit 0;
469 }
470
471 1;