]>
Commit | Line | Data |
---|---|---|
e143e9d8 DM |
1 | package PVE::CLIHandler; |
2 | ||
3 | use strict; | |
4 | use warnings; | |
340c9862 | 5 | use JSON; |
e143e9d8 | 6 | |
93ddd7bc | 7 | use PVE::SafeSyslog; |
e143e9d8 DM |
8 | use PVE::Exception qw(raise raise_param_exc); |
9 | use PVE::RESTHandler; | |
0da61ab3 | 10 | use PVE::PTY; |
881eb755 | 11 | use PVE::INotify; |
e143e9d8 DM |
12 | |
13 | use base qw(PVE::RESTHandler); | |
14 | ||
c1059f7c TL |
15 | # $cmddef defines which (sub)commands are available in a specific CLI class. |
16 | # A real command is always an array consisting of its class, name, array of | |
17 | # position fixed (required) parameters and hash of predefined parameters when | |
18 | # mapping a CLI command t o an API call. Optionally an output method can be | |
19 | # passed at the end, e.g., for formatting or transformation purpose. | |
20 | # | |
21 | # [class, name, fixed_params, API_pre-set params, output_sub ] | |
22 | # | |
23 | # In case of so called 'simple commands', the $cmddef can be also just an | |
24 | # array. | |
25 | # | |
26 | # Examples: | |
27 | # $cmddef = { | |
28 | # command => [ 'PVE::API2::Class', 'command', [ 'arg1', 'arg2' ], { node => $nodename } ], | |
29 | # do => { | |
30 | # this => [ 'PVE::API2::OtherClass', 'method', [ 'arg1' ], undef, sub { | |
31 | # my ($res) = @_; | |
32 | # print "$res\n"; | |
33 | # }], | |
34 | # that => [ 'PVE::API2::OtherClass', 'subroutine' [] ], | |
35 | # }, | |
36 | # dothat => { alias => 'do that' }, | |
37 | # } | |
e143e9d8 DM |
38 | my $cmddef; |
39 | my $exename; | |
891b798d | 40 | my $cli_handler_class; |
e143e9d8 | 41 | |
37f010e7 TL |
42 | my $standard_mappings = { |
43 | 'pve-password' => { | |
44 | name => 'password', | |
45 | desc => '<password>', | |
46 | interactive => 1, | |
47 | func => sub { | |
48 | my ($value) = @_; | |
49 | return $value if $value; | |
50 | return PVE::PTY::get_confirmed_password(); | |
51 | }, | |
52 | }, | |
53 | }; | |
54 | sub get_standard_mapping { | |
55 | my ($name, $base) = @_; | |
56 | ||
57 | my $std = $standard_mappings->{$name}; | |
58 | die "no such standard mapping '$name'\n" if !$std; | |
59 | ||
60 | my $res = $base || {}; | |
61 | ||
62 | foreach my $opt (keys %$std) { | |
63 | next if defined($res->{$opt}); | |
64 | $res->{$opt} = $std->{$opt}; | |
65 | } | |
66 | ||
67 | return $res; | |
68 | } | |
69 | ||
4842b651 DC |
70 | my $gen_param_mapping_func = sub { |
71 | my ($cli_handler_class) = @_; | |
72 | ||
73 | my $param_mapping = $cli_handler_class->can('param_mapping'); | |
74 | ||
75 | if (!$param_mapping) { | |
76 | my $read_password = $cli_handler_class->can('read_password'); | |
77 | my $string_param_mapping = $cli_handler_class->can('string_param_file_mapping'); | |
78 | ||
79 | return $string_param_mapping if !$read_password; | |
80 | ||
81 | $param_mapping = sub { | |
82 | my ($name) = @_; | |
83 | ||
84 | my $password_map = get_standard_mapping('pve-password', { | |
85 | func => $read_password | |
86 | }); | |
87 | my $map = $string_param_mapping ? $string_param_mapping->($name) : []; | |
88 | return [@$map, $password_map]; | |
89 | }; | |
90 | } | |
91 | ||
92 | return $param_mapping; | |
93 | }; | |
94 | ||
d204696c TL |
95 | my $assert_initialized = sub { |
96 | my @caller = caller; | |
97 | die "$caller[0]:$caller[2] - not initialized\n" | |
98 | if !($cmddef && $exename && $cli_handler_class); | |
99 | }; | |
100 | ||
918140af TL |
101 | my $abort = sub { |
102 | my ($reason, $cmd) = @_; | |
103 | print_usage_short (\*STDERR, $reason, $cmd); | |
104 | exit (-1); | |
105 | }; | |
106 | ||
e143e9d8 DM |
107 | my $expand_command_name = sub { |
108 | my ($def, $cmd) = @_; | |
109 | ||
5082a17b WB |
110 | return $cmd if exists $def->{$cmd}; # command is already complete |
111 | ||
ea5a5084 | 112 | my $is_alias = sub { ref($_[0]) eq 'HASH' && exists($_[0]->{alias}) }; |
0b796806 TL |
113 | my @expanded = grep { /^\Q$cmd\E/ && !$is_alias->($def->{$_}) } keys %$def; |
114 | ||
5082a17b WB |
115 | return $expanded[0] if scalar(@expanded) == 1; # enforce exact match |
116 | ||
117 | return undef; | |
e143e9d8 DM |
118 | }; |
119 | ||
50b89b88 TL |
120 | my $get_commands = sub { |
121 | my $def = shift // die "no command definition passed!"; | |
122 | return [ grep { !(ref($def->{$_}) eq 'HASH' && defined($def->{$_}->{alias})) } sort keys %$def ]; | |
edf3d572 DM |
123 | }; |
124 | ||
50b89b88 TL |
125 | my $complete_command_names = sub { $get_commands->($cmddef) }; |
126 | ||
127 | # traverses the command definition using the $argv array, resolving one level | |
128 | # of aliases. | |
129 | # Returns the matching (sub) command and its definition, and argument array for | |
130 | # this (sub) command and a hash where we marked which (sub) commands got | |
131 | # expanded (e.g. st => status) while traversing | |
132 | sub resolve_cmd { | |
133 | my ($argv, $is_alias) = @_; | |
134 | ||
135 | my ($def, $cmd) = ($cmddef, $argv); | |
f9326469 | 136 | my $cmdstr = $exename; |
50b89b88 TL |
137 | |
138 | if (ref($argv) eq 'ARRAY') { | |
5082a17b | 139 | my $expanded_last_arg; |
50b89b88 TL |
140 | my $last_arg_id = scalar(@$argv) - 1; |
141 | ||
142 | for my $i (0..$last_arg_id) { | |
143 | $cmd = $expand_command_name->($def, $argv->[$i]); | |
5082a17b WB |
144 | if (defined($cmd)) { |
145 | # If the argument was expanded (or was already complete) and it | |
146 | # is the final argument, tell our caller about it: | |
147 | $expanded_last_arg = $cmd if $i == $last_arg_id; | |
148 | } else { | |
149 | # Otherwise continue with the unexpanded version of it. | |
150 | $cmd = $argv->[$i]; | |
151 | } | |
f9326469 | 152 | $cmdstr .= " $cmd"; |
50b89b88 | 153 | $def = $def->{$cmd}; |
57c0d0c6 | 154 | last if !defined($def); |
50b89b88 TL |
155 | |
156 | if (ref($def) eq 'ARRAY') { | |
157 | # could expand to a real command, rest of $argv are its arguments | |
158 | my $cmd_args = [ @$argv[$i+1..$last_arg_id] ]; | |
5082a17b | 159 | return ($cmd, $def, $cmd_args, $expanded_last_arg, $cmdstr); |
50b89b88 TL |
160 | } |
161 | ||
162 | if (defined($def->{alias})) { | |
163 | die "alias loop detected for '$cmd'" if $is_alias; # avoids cycles | |
164 | # replace aliased (sub)command with the expanded aliased command | |
165 | splice @$argv, $i, 1, split(/ +/, $def->{alias}); | |
166 | return resolve_cmd($argv, 1); | |
167 | } | |
168 | } | |
169 | # got either a special command (bashcomplete, verifyapi) or an unknown | |
170 | # cmd, just return first entry as cmd and the rest of $argv as cmd_arg | |
171 | my $cmd_args = [ @$argv[1..$last_arg_id] ]; | |
5082a17b | 172 | return ($argv->[0], $def, $cmd_args, $expanded_last_arg, $cmdstr); |
50b89b88 | 173 | } |
f9326469 | 174 | return ($cmd, $def, undef, undef, $cmdstr); |
50b89b88 TL |
175 | } |
176 | ||
4c802a57 TL |
177 | sub generate_usage_str { |
178 | my ($format, $cmd, $indent, $separator, $sortfunc) = @_; | |
179 | ||
180 | $assert_initialized->(); | |
181 | die 'format required' if !$format; | |
182 | ||
183 | $sortfunc //= sub { sort keys %{$_[0]} }; | |
184 | $separator //= ''; | |
185 | $indent //= ''; | |
186 | ||
968bcf45 | 187 | my $param_cb = $gen_param_mapping_func->($cli_handler_class); |
4c802a57 | 188 | |
f9326469 | 189 | my ($subcmd, $def, undef, undef, $cmdstr) = resolve_cmd($cmd); |
24ccf353 | 190 | $abort->("unknown command '$cmdstr'") if !defined($def) && ref($cmd) eq 'ARRAY'; |
4c802a57 TL |
191 | |
192 | my $generate; | |
193 | $generate = sub { | |
194 | my ($indent, $separator, $def, $prefix) = @_; | |
195 | ||
196 | my $str = ''; | |
197 | if (ref($def) eq 'HASH') { | |
198 | my $oldclass = undef; | |
199 | foreach my $cmd (&$sortfunc($def)) { | |
200 | ||
201 | if (ref($def->{$cmd}) eq 'ARRAY') { | |
202 | my ($class, $name, $arg_param, $fixed_param) = @{$def->{$cmd}}; | |
203 | ||
204 | $str .= $separator if $oldclass && $oldclass ne $class; | |
205 | $str .= $indent; | |
206 | $str .= $class->usage_str($name, "$prefix $cmd", $arg_param, | |
968bcf45 | 207 | $fixed_param, $format, $param_cb); |
4c802a57 | 208 | $oldclass = $class; |
50b89b88 TL |
209 | |
210 | } elsif (defined($def->{$cmd}->{alias}) && ($format eq 'asciidoc')) { | |
211 | ||
212 | $str .= "*$prefix $cmd*\n\nAn alias for '$exename $def->{$cmd}->{alias}'.\n\n"; | |
213 | ||
214 | } else { | |
215 | next if $def->{$cmd}->{alias}; | |
216 | ||
217 | my $substr = $generate->($indent, $separator, $def->{$cmd}, "$prefix $cmd"); | |
218 | if ($substr) { | |
219 | $substr .= $separator if $substr !~ /\Q$separator\E{2}/; | |
220 | $str .= $substr; | |
221 | } | |
4c802a57 TL |
222 | } |
223 | ||
224 | } | |
225 | } else { | |
226 | my ($class, $name, $arg_param, $fixed_param) = @$def; | |
227 | $abort->("unknown command '$cmd'") if !$class; | |
228 | ||
229 | $str .= $indent; | |
968bcf45 | 230 | $str .= $class->usage_str($name, $prefix, $arg_param, $fixed_param, $format, $param_cb); |
4c802a57 TL |
231 | } |
232 | return $str; | |
233 | }; | |
234 | ||
50b89b88 | 235 | return $generate->($indent, $separator, $def, $cmdstr); |
4c802a57 TL |
236 | } |
237 | ||
e143e9d8 | 238 | __PACKAGE__->register_method ({ |
3ef20687 | 239 | name => 'help', |
e143e9d8 DM |
240 | path => 'help', |
241 | method => 'GET', | |
242 | description => "Get help about specified command.", | |
243 | parameters => { | |
3ef20687 | 244 | additionalProperties => 0, |
e143e9d8 | 245 | properties => { |
6627ae09 TL |
246 | 'extra-args' => PVE::JSONSchema::get_standard_option('extra-args', { |
247 | description => 'Shows help for a specific command', | |
edf3d572 | 248 | completion => $complete_command_names, |
6627ae09 | 249 | }), |
e143e9d8 DM |
250 | verbose => { |
251 | description => "Verbose output format.", | |
252 | type => 'boolean', | |
253 | optional => 1, | |
254 | }, | |
255 | }, | |
256 | }, | |
257 | returns => { type => 'null' }, | |
3ef20687 | 258 | |
e143e9d8 DM |
259 | code => sub { |
260 | my ($param) = @_; | |
261 | ||
d204696c | 262 | $assert_initialized->(); |
e143e9d8 | 263 | |
6627ae09 | 264 | my $cmd = $param->{'extra-args'}; |
e143e9d8 | 265 | |
6627ae09 | 266 | my $verbose = defined($cmd) && $cmd; |
e143e9d8 DM |
267 | $verbose = $param->{verbose} if defined($param->{verbose}); |
268 | ||
269 | if (!$cmd) { | |
270 | if ($verbose) { | |
271 | print_usage_verbose(); | |
3ef20687 | 272 | } else { |
e143e9d8 DM |
273 | print_usage_short(\*STDOUT); |
274 | } | |
275 | return undef; | |
276 | } | |
277 | ||
4c802a57 TL |
278 | my $str; |
279 | if ($verbose) { | |
280 | $str = generate_usage_str('full', $cmd, ''); | |
281 | } else { | |
282 | $str = generate_usage_str('short', $cmd, ' ' x 7); | |
283 | } | |
284 | $str =~ s/^\s+//; | |
e143e9d8 | 285 | |
e143e9d8 DM |
286 | if ($verbose) { |
287 | print "$str\n"; | |
288 | } else { | |
289 | print "USAGE: $str\n"; | |
290 | } | |
291 | ||
292 | return undef; | |
293 | ||
294 | }}); | |
295 | ||
0a5a1eee | 296 | sub print_simple_asciidoc_synopsis { |
d204696c | 297 | $assert_initialized->(); |
fe3f1fde | 298 | |
4c802a57 TL |
299 | my $synopsis = "*${exename}* `help`\n\n"; |
300 | $synopsis .= generate_usage_str('asciidoc'); | |
fe3f1fde DM |
301 | |
302 | return $synopsis; | |
303 | } | |
304 | ||
0a5a1eee | 305 | sub print_asciidoc_synopsis { |
d204696c | 306 | $assert_initialized->(); |
fe3f1fde | 307 | |
fe3f1fde DM |
308 | my $synopsis = ""; |
309 | ||
310 | $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n"; | |
311 | ||
4c802a57 | 312 | $synopsis .= generate_usage_str('asciidoc'); |
fe3f1fde DM |
313 | |
314 | $synopsis .= "\n"; | |
315 | ||
316 | return $synopsis; | |
317 | } | |
318 | ||
e143e9d8 | 319 | sub print_usage_verbose { |
d204696c | 320 | $assert_initialized->(); |
891b798d | 321 | |
e143e9d8 DM |
322 | print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n"; |
323 | ||
4c802a57 | 324 | my $str = generate_usage_str('full'); |
e143e9d8 | 325 | |
4c802a57 | 326 | print "$str\n"; |
e143e9d8 DM |
327 | } |
328 | ||
329 | sub print_usage_short { | |
50b89b88 | 330 | my ($fd, $msg, $cmd) = @_; |
e143e9d8 | 331 | |
d204696c | 332 | $assert_initialized->(); |
891b798d | 333 | |
e143e9d8 DM |
334 | print $fd "ERROR: $msg\n" if $msg; |
335 | print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n"; | |
336 | ||
50b89b88 | 337 | print {$fd} generate_usage_str('short', $cmd, ' ' x 7, "\n", sub { |
4c802a57 TL |
338 | my ($h) = @_; |
339 | return sort { | |
340 | if (ref($h->{$a}) eq 'ARRAY' && ref($h->{$b}) eq 'ARRAY') { | |
341 | # $a and $b are both real commands order them by their class | |
342 | return $h->{$a}->[0] cmp $h->{$b}->[0] || $a cmp $b; | |
50b89b88 TL |
343 | } elsif (ref($h->{$a}) eq 'ARRAY' xor ref($h->{$b}) eq 'ARRAY') { |
344 | # real command and subcommand mixed, put sub commands first | |
345 | return ref($h->{$b}) eq 'ARRAY' ? -1 : 1; | |
4c802a57 | 346 | } else { |
50b89b88 | 347 | # both are either from the same class or subcommands |
4c802a57 TL |
348 | return $a cmp $b; |
349 | } | |
350 | } keys %$h; | |
351 | }); | |
e143e9d8 DM |
352 | } |
353 | ||
d8053c08 | 354 | my $print_bash_completion = sub { |
57e67ea3 | 355 | my ($simple_cmd, $bash_command, $cur, $prev) = @_; |
d8053c08 DM |
356 | |
357 | my $debug = 0; | |
358 | ||
359 | return if !(defined($cur) && defined($prev) && defined($bash_command)); | |
360 | return if !defined($ENV{COMP_LINE}); | |
361 | return if !defined($ENV{COMP_POINT}); | |
362 | ||
363 | my $cmdline = substr($ENV{COMP_LINE}, 0, $ENV{COMP_POINT}); | |
364 | print STDERR "\nCMDLINE: $ENV{COMP_LINE}\n" if $debug; | |
365 | ||
58d9e664 | 366 | my $args = PVE::Tools::split_args($cmdline); |
5fa768fc | 367 | shift @$args; # no need for program name |
d8053c08 DM |
368 | my $print_result = sub { |
369 | foreach my $p (@_) { | |
2c48a665 | 370 | print "$p\n" if $p =~ m/^\Q$cur\E/; |
d8053c08 DM |
371 | } |
372 | }; | |
373 | ||
5fa768fc TL |
374 | my ($cmd, $def) = ($simple_cmd, $cmddef); |
375 | if (!$simple_cmd) { | |
0ed80698 | 376 | ($cmd, $def, $args, my $expanded) = resolve_cmd($args); |
50b89b88 | 377 | |
5082a17b WB |
378 | if (defined($expanded) && $prev ne $expanded) { |
379 | print "$expanded\n"; | |
50b89b88 TL |
380 | return; |
381 | } | |
5082a17b WB |
382 | |
383 | if (ref($def) eq 'HASH') { | |
384 | &$print_result(@{$get_commands->($def)}); | |
d8053c08 DM |
385 | return; |
386 | } | |
d8053c08 | 387 | } |
d8053c08 DM |
388 | return if !$def; |
389 | ||
5fa768fc TL |
390 | my $pos = scalar(@$args) - 1; |
391 | $pos += 1 if $cmdline =~ m/\s+$/; | |
392 | print STDERR "pos: $pos\n" if $debug; | |
393 | return if $pos < 0; | |
d8053c08 DM |
394 | |
395 | my $skip_param = {}; | |
396 | ||
397 | my ($class, $name, $arg_param, $uri_param) = @$def; | |
398 | $arg_param //= []; | |
399 | $uri_param //= {}; | |
400 | ||
d90a2fd0 DM |
401 | $arg_param = [ $arg_param ] if !ref($arg_param); |
402 | ||
d8053c08 DM |
403 | map { $skip_param->{$_} = 1; } @$arg_param; |
404 | map { $skip_param->{$_} = 1; } keys %$uri_param; | |
405 | ||
d8053c08 DM |
406 | my $info = $class->map_method_by_name($name); |
407 | ||
5fa768fc | 408 | my $prop = $info->{parameters}->{properties}; |
d8053c08 DM |
409 | |
410 | my $print_parameter_completion = sub { | |
411 | my ($pname) = @_; | |
412 | my $d = $prop->{$pname}; | |
413 | if ($d->{completion}) { | |
414 | my $vt = ref($d->{completion}); | |
415 | if ($vt eq 'CODE') { | |
58d9e664 | 416 | my $res = $d->{completion}->($cmd, $pname, $cur, $args); |
d8053c08 DM |
417 | &$print_result(@$res); |
418 | } | |
419 | } elsif ($d->{type} eq 'boolean') { | |
420 | &$print_result('0', '1'); | |
421 | } elsif ($d->{enum}) { | |
422 | &$print_result(@{$d->{enum}}); | |
423 | } | |
424 | }; | |
425 | ||
426 | # positional arguments | |
5fa768fc TL |
427 | if ($pos < scalar(@$arg_param)) { |
428 | my $pname = $arg_param->[$pos]; | |
d8053c08 DM |
429 | &$print_parameter_completion($pname); |
430 | return; | |
431 | } | |
432 | ||
433 | my @option_list = (); | |
434 | foreach my $key (keys %$prop) { | |
435 | next if $skip_param->{$key}; | |
436 | push @option_list, "--$key"; | |
437 | } | |
438 | ||
439 | if ($cur =~ m/^-/) { | |
440 | &$print_result(@option_list); | |
441 | return; | |
442 | } | |
443 | ||
444 | if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) { | |
445 | my $pname = $1; | |
446 | &$print_parameter_completion($pname); | |
447 | return; | |
448 | } | |
449 | ||
450 | &$print_result(@option_list); | |
451 | }; | |
452 | ||
340c9862 DM |
453 | sub data_to_text { |
454 | my ($data) = @_; | |
455 | ||
16f20332 | 456 | return '' if !defined($data); |
340c9862 DM |
457 | |
458 | if (my $class = ref($data)) { | |
459 | return to_json($data, { utf8 => 1, canonical => 1 }); | |
460 | } else { | |
461 | return "$data"; | |
462 | } | |
463 | } | |
464 | ||
8042c2cc | 465 | # prints a formatted table with a title row. |
8dd3280b DM |
466 | # $data - the data to print (array of objects) |
467 | # $returnprops -json schema property description | |
468 | # $props_to_print - ordered list of properties to print | |
9ac6416e TL |
469 | # $sort_key can be used to sort after a column, if it isn't set we sort |
470 | # after the leftmost column (with no undef value in $data) this can be | |
471 | # turned off by passing 0 as $sort_key | |
8042c2cc | 472 | sub print_text_table { |
8dd3280b | 473 | my ($data, $returnprops, $props_to_print, $sort_key) = @_; |
85b9def2 | 474 | |
9ac6416e TL |
475 | my $autosort = 1; |
476 | if (defined($sort_key) && $sort_key eq 0) { | |
477 | $autosort = 0; | |
505786f6 DM |
478 | $sort_key = undef; |
479 | } | |
480 | ||
8dd3280b DM |
481 | my $colopts = {}; |
482 | my $formatstring = ''; | |
483 | ||
484 | my $column_count = scalar(@$props_to_print); | |
485 | ||
486 | for (my $i = 0; $i < $column_count; $i++) { | |
487 | my $prop = $props_to_print->[$i]; | |
ffe4449c | 488 | my $propinfo = $returnprops->{$prop} // {}; |
8042c2cc | 489 | |
8dd3280b DM |
490 | my $title = $propinfo->{title} // $prop; |
491 | my $cutoff = $propinfo->{print_width} // $propinfo->{maxLength}; | |
8042c2cc | 492 | |
85b9def2 | 493 | # calculate maximal print width and cutoff |
8042c2cc SI |
494 | my $titlelen = length($title); |
495 | ||
496 | my $longest = $titlelen; | |
505786f6 | 497 | my $sortable = $autosort; |
8042c2cc | 498 | foreach my $entry (@$data) { |
8dd3280b | 499 | my $len = length(data_to_text($entry->{$prop})) // 0; |
8042c2cc | 500 | $longest = $len if $len > $longest; |
8dd3280b | 501 | $sortable = 0 if !defined($entry->{$prop}); |
8042c2cc | 502 | } |
83794659 | 503 | $cutoff = $longest if !defined($cutoff) || $cutoff > $longest; |
8dd3280b | 504 | $sort_key //= $prop if $sortable; |
8042c2cc | 505 | |
8dd3280b DM |
506 | $colopts->{$prop} = { |
507 | title => $title, | |
508 | default => $propinfo->{default} // '', | |
509 | cutoff => $cutoff, | |
510 | }; | |
511 | ||
83794659 | 512 | # skip alignment and cutoff on last column |
8dd3280b | 513 | $formatstring .= ($i == ($column_count - 1)) ? "%s\n" : "%-${cutoff}s "; |
8042c2cc SI |
514 | } |
515 | ||
8dd3280b | 516 | printf $formatstring, map { $colopts->{$_}->{title} } @$props_to_print; |
8042c2cc | 517 | |
8dd3280b | 518 | if (defined($sort_key)) { |
3c3d1e07 | 519 | my $type = $returnprops->{$sort_key}->{type} // 'string'; |
83794659 | 520 | if ($type eq 'integer' || $type eq 'number') { |
8dd3280b DM |
521 | @$data = sort { $a->{$sort_key} <=> $b->{$sort_key} } @$data; |
522 | } else { | |
523 | @$data = sort { $a->{$sort_key} cmp $b->{$sort_key} } @$data; | |
524 | } | |
e05f7cdd | 525 | } |
8dd3280b | 526 | |
e05f7cdd | 527 | foreach my $entry (@$data) { |
8dd3280b DM |
528 | printf $formatstring, map { |
529 | substr(data_to_text($entry->{$_}) // $colopts->{$_}->{default}, | |
530 | 0, $colopts->{$_}->{cutoff}); | |
531 | } @$props_to_print; | |
8042c2cc SI |
532 | } |
533 | } | |
534 | ||
db5b22d1 SI |
535 | # prints the result of an API GET call returning an array as a table. |
536 | # takes formatting information from the results property of the call | |
537 | # if $props_to_print is provided, prints only those columns. otherwise | |
538 | # takes all fields of the results property, with a fallback | |
539 | # to all fields occuring in items of $data. | |
a604bf22 | 540 | sub print_api_list { |
505786f6 | 541 | my ($data, $result_schema, $props_to_print, $sort_key) = @_; |
85b9def2 | 542 | |
2edb0abb | 543 | die "can only print object lists\n" |
ec3cbded | 544 | if !($result_schema->{type} eq 'array' && $result_schema->{items}->{type} eq 'object'); |
305fc1e1 | 545 | |
ec3cbded | 546 | my $returnprops = $result_schema->{items}->{properties}; |
85b9def2 | 547 | |
eb04f1e2 DM |
548 | if (!defined($props_to_print)) { |
549 | $props_to_print = [ sort keys %$returnprops ]; | |
550 | if (!scalar(@$props_to_print)) { | |
9b8f2f8f SI |
551 | my $all_props = {}; |
552 | foreach my $obj (@{$data}) { | |
553 | foreach my $key (keys %{$obj}) { | |
554 | $all_props->{ $key } = 1; | |
555 | } | |
556 | } | |
557 | $props_to_print = [ sort keys %{$all_props} ]; | |
eb04f1e2 DM |
558 | } |
559 | die "unable to detect list properties\n" if !scalar(@$props_to_print); | |
560 | } | |
561 | ||
8dd3280b | 562 | print_text_table($data, $returnprops, $props_to_print, $sort_key); |
a604bf22 SI |
563 | } |
564 | ||
340c9862 | 565 | sub print_api_result { |
505786f6 | 566 | my ($format, $data, $result_schema, $props_to_print, $sort_key) = @_; |
340c9862 DM |
567 | |
568 | return if $result_schema->{type} eq 'null'; | |
569 | ||
570 | if ($format eq 'json') { | |
571 | print to_json($data, {utf8 => 1, allow_nonref => 1, canonical => 1, pretty => 1 }); | |
572 | } elsif ($format eq 'text') { | |
573 | my $type = $result_schema->{type}; | |
574 | if ($type eq 'object') { | |
fa7d20bf TL |
575 | $props_to_print = [ sort keys %$data ] if !defined($props_to_print); |
576 | foreach my $key (@$props_to_print) { | |
577 | print $key . ": " . data_to_text($data->{$key}) . "\n"; | |
340c9862 DM |
578 | } |
579 | } elsif ($type eq 'array') { | |
580 | return if !scalar(@$data); | |
581 | my $item_type = $result_schema->{items}->{type}; | |
582 | if ($item_type eq 'object') { | |
505786f6 | 583 | print_api_list($data, $result_schema, $props_to_print, $sort_key); |
340c9862 DM |
584 | } else { |
585 | foreach my $entry (@$data) { | |
586 | print data_to_text($entry) . "\n"; | |
587 | } | |
588 | } | |
589 | } else { | |
590 | print "$data\n"; | |
591 | } | |
592 | } else { | |
593 | die "internal error: unknown output format"; # should not happen | |
594 | } | |
595 | } | |
596 | ||
1f130ba6 DM |
597 | sub verify_api { |
598 | my ($class) = @_; | |
599 | ||
600 | # simply verify all registered methods | |
601 | PVE::RESTHandler::validate_method_schemas(); | |
602 | } | |
603 | ||
8f3712f8 DM |
604 | my $get_exe_name = sub { |
605 | my ($class) = @_; | |
3ef20687 | 606 | |
8f3712f8 DM |
607 | my $name = $class; |
608 | $name =~ s/^.*:://; | |
609 | $name =~ s/_/-/g; | |
610 | ||
611 | return $name; | |
612 | }; | |
613 | ||
c45707a0 DM |
614 | sub generate_bash_completions { |
615 | my ($class) = @_; | |
616 | ||
617 | # generate bash completion config | |
618 | ||
8f3712f8 | 619 | $exename = &$get_exe_name($class); |
c45707a0 DM |
620 | |
621 | print <<__EOD__; | |
622 | # $exename bash completion | |
623 | ||
624 | # see http://tiswww.case.edu/php/chet/bash/FAQ | |
625 | # and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion | |
626 | # this modifies global var, but I found no better way | |
627 | COMP_WORDBREAKS=\${COMP_WORDBREAKS//:} | |
628 | ||
e4a1d8e2 | 629 | complete -o default -C '$exename bashcomplete' $exename |
c45707a0 DM |
630 | __EOD__ |
631 | } | |
632 | ||
fe3f1fde DM |
633 | sub generate_asciidoc_synopsys { |
634 | my ($class) = @_; | |
0a5a1eee FG |
635 | $class->generate_asciidoc_synopsis(); |
636 | }; | |
637 | ||
638 | sub generate_asciidoc_synopsis { | |
639 | my ($class) = @_; | |
fe3f1fde DM |
640 | |
641 | $cli_handler_class = $class; | |
642 | ||
643 | $exename = &$get_exe_name($class); | |
644 | ||
645 | no strict 'refs'; | |
646 | my $def = ${"${class}::cmddef"}; | |
57e67ea3 | 647 | $cmddef = $def; |
fe3f1fde DM |
648 | |
649 | if (ref($def) eq 'ARRAY') { | |
4c802a57 | 650 | print_simple_asciidoc_synopsis(); |
fe3f1fde | 651 | } else { |
fe3f1fde DM |
652 | $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ]; |
653 | ||
0a5a1eee | 654 | print_asciidoc_synopsis(); |
fe3f1fde DM |
655 | } |
656 | } | |
657 | ||
7b7f99c9 DM |
658 | # overwrite this if you want to run/setup things early |
659 | sub setup_environment { | |
660 | my ($class) = @_; | |
661 | ||
662 | # do nothing by default | |
663 | } | |
664 | ||
891b798d | 665 | my $handle_cmd = sub { |
968bcf45 | 666 | my ($args, $preparefunc, $param_cb) = @_; |
e143e9d8 | 667 | |
6627ae09 | 668 | $cmddef->{help} = [ __PACKAGE__, 'help', ['extra-args'] ]; |
e143e9d8 | 669 | |
f9326469 | 670 | my ($cmd, $def, $cmd_args, undef, $cmd_str) = resolve_cmd($args); |
7b7f99c9 | 671 | |
918140af TL |
672 | $abort->("no command specified") if !$cmd; |
673 | ||
674 | # call verifyapi before setup_environment(), don't execute any real code in | |
675 | # this case | |
676 | if ($cmd eq 'verifyapi') { | |
e143e9d8 DM |
677 | PVE::RESTHandler::validate_method_schemas(); |
678 | return; | |
7b7f99c9 DM |
679 | } |
680 | ||
681 | $cli_handler_class->setup_environment(); | |
682 | ||
683 | if ($cmd eq 'bashcomplete') { | |
50b89b88 | 684 | &$print_bash_completion(undef, @$cmd_args); |
d8053c08 | 685 | return; |
e143e9d8 DM |
686 | } |
687 | ||
50b89b88 | 688 | # checked special commands, if def is still a hash we got an incomplete sub command |
131f316b | 689 | $abort->("incomplete command '$cmd_str'", $args) if ref($def) eq 'HASH'; |
8e3e9929 | 690 | |
50b89b88 | 691 | &$preparefunc() if $preparefunc; |
e143e9d8 | 692 | |
b8dc4366 | 693 | my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def || []}; |
50b89b88 | 694 | $abort->("unknown command '$cmd_str'") if !$class; |
e143e9d8 | 695 | |
968bcf45 | 696 | my $res = $class->cli_handler($cmd_str, $name, $cmd_args, $arg_param, $uri_param, $param_cb); |
2026f4b5 | 697 | |
a604bf22 | 698 | if (defined $outsub) { |
ec3cbded DM |
699 | my $result_schema = $class->map_method_by_name($name)->{returns}; |
700 | $outsub->($res, $result_schema); | |
a604bf22 | 701 | } |
891b798d | 702 | }; |
2026f4b5 | 703 | |
891b798d | 704 | my $handle_simple_cmd = sub { |
968bcf45 | 705 | my ($args, $preparefunc, $param_cb) = @_; |
2026f4b5 | 706 | |
57e67ea3 | 707 | my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef}; |
2026f4b5 DM |
708 | die "no class specified" if !$class; |
709 | ||
d8053c08 | 710 | if (scalar(@$args) >= 1) { |
2026f4b5 DM |
711 | if ($args->[0] eq 'help') { |
712 | my $str = "USAGE: $name help\n"; | |
4c802a57 | 713 | $str .= generate_usage_str('long'); |
2026f4b5 DM |
714 | print STDERR "$str\n\n"; |
715 | return; | |
716 | } elsif ($args->[0] eq 'verifyapi') { | |
717 | PVE::RESTHandler::validate_method_schemas(); | |
718 | return; | |
2026f4b5 | 719 | } |
e143e9d8 | 720 | } |
2026f4b5 | 721 | |
7b7f99c9 DM |
722 | $cli_handler_class->setup_environment(); |
723 | ||
724 | if (scalar(@$args) >= 1) { | |
725 | if ($args->[0] eq 'bashcomplete') { | |
726 | shift @$args; | |
57e67ea3 | 727 | &$print_bash_completion($name, @$args); |
7b7f99c9 DM |
728 | return; |
729 | } | |
730 | } | |
731 | ||
7fe1f565 DM |
732 | &$preparefunc() if $preparefunc; |
733 | ||
968bcf45 | 734 | my $res = $class->cli_handler($name, $name, \@ARGV, $arg_param, $uri_param, $param_cb); |
2026f4b5 | 735 | |
a604bf22 | 736 | if (defined $outsub) { |
ec3cbded DM |
737 | my $result_schema = $class->map_method_by_name($name)->{returns}; |
738 | $outsub->($res, $result_schema); | |
a604bf22 | 739 | } |
891b798d DM |
740 | }; |
741 | ||
891b798d DM |
742 | sub run_cli_handler { |
743 | my ($class, %params) = @_; | |
744 | ||
745 | $cli_handler_class = $class; | |
746 | ||
747 | $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin'; | |
748 | ||
aa9b9af5 | 749 | foreach my $key (keys %params) { |
5ae87c41 | 750 | next if $key eq 'prepare'; |
1042b82c DM |
751 | next if $key eq 'no_init'; # not used anymore |
752 | next if $key eq 'no_rpcenv'; # not used anymore | |
aa9b9af5 DM |
753 | die "unknown parameter '$key'"; |
754 | } | |
755 | ||
5ae87c41 | 756 | my $preparefunc = $params{prepare}; |
891b798d | 757 | |
968bcf45 | 758 | my $param_cb = $gen_param_mapping_func->($cli_handler_class); |
891b798d DM |
759 | |
760 | $exename = &$get_exe_name($class); | |
761 | ||
762 | initlog($exename); | |
763 | ||
891b798d | 764 | no strict 'refs'; |
57e67ea3 | 765 | $cmddef = ${"${class}::cmddef"}; |
891b798d | 766 | |
57e67ea3 | 767 | if (ref($cmddef) eq 'ARRAY') { |
968bcf45 | 768 | $handle_simple_cmd->(\@ARGV, $preparefunc, $param_cb); |
891b798d | 769 | } else { |
968bcf45 | 770 | $handle_cmd->(\@ARGV, $preparefunc, $param_cb); |
891b798d DM |
771 | } |
772 | ||
773 | exit 0; | |
e143e9d8 DM |
774 | } |
775 | ||
776 | 1; |