]> git.proxmox.com Git - pve-common.git/blame - src/PVE/RESTHandler.pm
PVE::CLIFormatter::print_api_result - remove parameter $format
[pve-common.git] / src / PVE / RESTHandler.pm
CommitLineData
e143e9d8
DM
1package PVE::RESTHandler;
2
3use strict;
4no strict 'refs'; # our autoload requires this
e143e9d8
DM
5use warnings;
6use PVE::SafeSyslog;
7use PVE::Exception qw(raise raise_param_exc);
8use PVE::JSONSchema;
dfc6cff8 9use PVE::Tools;
e143e9d8
DM
10use HTTP::Status qw(:constants :is status_message);
11use Text::Wrap;
4be9b5f7 12use Clone qw(clone);
e143e9d8
DM
13
14my $method_registry = {};
15my $method_by_name = {};
c1089794 16my $method_path_lookup = {};
e143e9d8
DM
17
18our $AUTOLOAD; # it's a package global
19
20sub api_clone_schema {
21 my ($schema) = @_;
22
23 my $res = {};
24 my $ref = ref($schema);
25 die "not a HASH reference" if !($ref && $ref eq 'HASH');
26
27 foreach my $k (keys %$schema) {
28 my $d = $schema->{$k};
29 if ($k ne 'properties') {
4be9b5f7 30 $res->{$k} = ref($d) ? clone($d) : $d;
e143e9d8
DM
31 next;
32 }
33 # convert indexed parameters like -net\d+ to -net[n]
34 foreach my $p (keys %$d) {
35 my $pd = $d->{$p};
36 if ($p =~ m/^([a-z]+)(\d+)$/) {
b546f33e 37 my ($name, $idx) = ($1, $2);
b54ad320 38 if ($idx == 0 && defined($d->{"${name}1"})) {
b546f33e
DM
39 $p = "${name}[n]";
40 } elsif (defined($d->{"${name}0"})) {
2c2a5fd3 41 next; # only handle once for -xx0, but only if -xx0 exists
e143e9d8
DM
42 }
43 }
534d4270
DM
44 my $tmp = ref($pd) ? clone($pd) : $pd;
45 # NOTE: add typetext property for more complex types, to
46 # make the web api viewer code simpler
47 if (!(defined($tmp->{enum}) || defined($tmp->{pattern}))) {
48 my $typetext = PVE::JSONSchema::schema_get_type_text($tmp);
49 if ($tmp->{type} && ($tmp->{type} ne $typetext)) {
50 $tmp->{typetext} = $typetext;
51 }
52 }
53 $res->{$k}->{$p} = $tmp;
e143e9d8
DM
54 }
55 }
56
57 return $res;
58}
59
60sub api_dump_full {
1e5ecf7b 61 my ($tree, $index, $class, $prefix, $raw_dump) = @_;
e143e9d8
DM
62
63 $prefix = '' if !$prefix;
64
65 my $ma = $method_registry->{$class};
66
67 foreach my $info (@$ma) {
68
69 my $path = "$prefix/$info->{path}";
70 $path =~ s/\/+$//;
71
72 if ($info->{subclass}) {
1e5ecf7b 73 api_dump_full($tree, $index, $info->{subclass}, $path, $raw_dump);
e143e9d8
DM
74 } else {
75 next if !$path;
76
77 # check if method is unique
78 my $realpath = $path;
79 $realpath =~ s/\{[^\}]+\}/\{\}/g;
80 my $fullpath = "$info->{method} $realpath";
81 die "duplicate path '$realpath'" if $index->{$fullpath};
82 $index->{$fullpath} = $info;
83
84 # insert into tree
85 my $treedir = $tree;
86 my $res;
87 my $sp = '';
88 foreach my $dir (split('/', $path)) {
89 next if !$dir;
90 $sp .= "/$dir";
91 $res = (grep { $_->{text} eq $dir } @$treedir)[0];
92 if ($res) {
93 $res->{children} = [] if !$res->{children};
94 $treedir = $res->{children};
95 } else {
96 $res = {
97 path => $sp,
98 text => $dir,
99 children => [],
100 };
101 push @$treedir, $res;
102 $treedir = $res->{children};
103 }
104 }
105
106 if ($res) {
107 my $data = {};
108 foreach my $k (keys %$info) {
109 next if $k eq 'code' || $k eq "match_name" || $k eq "match_re" ||
110 $k eq "path";
111
112 my $d = $info->{$k};
e143e9d8 113
1e5ecf7b
DM
114 if ($raw_dump) {
115 $data->{$k} = $d;
116 } else {
117 if ($k eq 'parameters') {
118 $data->{$k} = api_clone_schema($d);
119 } else {
120 $data->{$k} = ref($d) ? clone($d) : $d;
121 }
e143e9d8
DM
122 }
123 }
124 $res->{info}->{$info->{method}} = $data;
125 };
126 }
127 }
128};
129
130sub api_dump_cleanup_tree {
131 my ($tree) = @_;
132
133 foreach my $rec (@$tree) {
134 delete $rec->{children} if $rec->{children} && !scalar(@{$rec->{children}});
135 if ($rec->{children}) {
136 $rec->{leaf} = 0;
137 api_dump_cleanup_tree($rec->{children});
138 } else {
139 $rec->{leaf} = 1;
140 }
141 }
142
143}
144
903ea3ff
DM
145# api_dump_remove_refs: prepare API tree for use with to_json($tree)
146sub api_dump_remove_refs {
147 my ($tree) = @_;
148
149 my $class = ref($tree);
150 return $tree if !$class;
151
152 if ($class eq 'ARRAY') {
153 my $res = [];
154 foreach my $el (@$tree) {
155 push @$res, api_dump_remove_refs($el);
156 }
157 return $res;
158 } elsif ($class eq 'HASH') {
159 my $res = {};
160 foreach my $k (keys %$tree) {
161 if (my $itemclass = ref($tree->{$k})) {
162 if ($itemclass eq 'CODE') {
163 next if $k eq 'completion';
164 }
165 $res->{$k} = api_dump_remove_refs($tree->{$k});
166 } else {
167 $res->{$k} = $tree->{$k};
168 }
169 }
170 return $res;
171 } elsif ($class eq 'Regexp') {
172 return "$tree"; # return string representation
173 } else {
174 die "unknown class '$class'\n";
175 }
176}
177
e143e9d8 178sub api_dump {
1e5ecf7b 179 my ($class, $prefix, $raw_dump) = @_;
e143e9d8
DM
180
181 my $tree = [];
182
183 my $index = {};
1e5ecf7b 184 api_dump_full($tree, $index, $class, $prefix, $raw_dump);
e143e9d8
DM
185 api_dump_cleanup_tree($tree);
186 return $tree;
187};
188
189sub validate_method_schemas {
190
191 foreach my $class (keys %$method_registry) {
192 my $ma = $method_registry->{$class};
193
194 foreach my $info (@$ma) {
195 PVE::JSONSchema::validate_method_info($info);
196 }
197 }
198}
199
200sub register_method {
201 my ($self, $info) = @_;
202
203 my $match_re = [];
204 my $match_name = [];
205
c1089794
DM
206 my $errprefix;
207
208 my $method;
209 if ($info->{subclass}) {
210 $errprefix = "register subclass $info->{subclass} at ${self}/$info->{path} -";
211 $method = 'SUBCLASS';
212 } else {
213 $errprefix = "register method ${self}/$info->{path} -";
214 $info->{method} = 'GET' if !$info->{method};
215 $method = $info->{method};
216 }
217
218 $method_path_lookup->{$self} = {} if !defined($method_path_lookup->{$self});
219 my $path_lookup = $method_path_lookup->{$self};
220
221 die "$errprefix no path" if !defined($info->{path});
222
e143e9d8 223 foreach my $comp (split(/\/+/, $info->{path})) {
c1089794
DM
224 die "$errprefix path compoment has zero length\n" if $comp eq '';
225 my ($name, $regex);
e143e9d8 226 if ($comp =~ m/^\{(\w+)(:(.*))?\}$/) {
c1089794
DM
227 $name = $1;
228 $regex = $3 ? $3 : '\S+';
229 push @$match_re, $regex;
230 push @$match_name, $name;
e143e9d8 231 } else {
c1089794
DM
232 $name = $comp;
233 push @$match_re, $name;
234 push @$match_name, undef;
235 }
236
237 if ($regex) {
238 $path_lookup->{regex} = {} if !defined($path_lookup->{regex});
239
240 my $old_name = $path_lookup->{regex}->{match_name};
241 die "$errprefix found changed regex match name\n"
242 if defined($old_name) && ($old_name ne $name);
243 my $old_re = $path_lookup->{regex}->{match_re};
244 die "$errprefix found changed regex\n"
245 if defined($old_re) && ($old_re ne $regex);
246 $path_lookup->{regex}->{match_name} = $name;
247 $path_lookup->{regex}->{match_re} = $regex;
248
249 die "$errprefix path match error - regex and fixed items\n"
250 if defined($path_lookup->{folders});
251
252 $path_lookup = $path_lookup->{regex};
253
254 } else {
255 $path_lookup->{folders}->{$name} = {} if !defined($path_lookup->{folders}->{$name});
256
257 die "$errprefix path match error - regex and fixed items\n"
258 if defined($path_lookup->{regex});
259
260 $path_lookup = $path_lookup->{folders}->{$name};
e143e9d8
DM
261 }
262 }
263
c1089794
DM
264 die "$errprefix duplicate method definition\n"
265 if defined($path_lookup->{$method});
266
1dad1ca5
DM
267 if ($method eq 'SUBCLASS') {
268 foreach my $m (qw(GET PUT POST DELETE)) {
269 die "$errprefix duplicate method definition SUBCLASS and $m\n" if $path_lookup->{$m};
270 }
271 }
c1089794
DM
272 $path_lookup->{$method} = $info;
273
e143e9d8
DM
274 $info->{match_re} = $match_re;
275 $info->{match_name} = $match_name;
276
277 $method_by_name->{$self} = {} if !defined($method_by_name->{$self});
278
279 if ($info->{name}) {
c1089794 280 die "$errprefix method name already defined\n"
e143e9d8
DM
281 if defined($method_by_name->{$self}->{$info->{name}});
282
283 $method_by_name->{$self}->{$info->{name}} = $info;
284 }
285
286 push @{$method_registry->{$self}}, $info;
287}
288
f1fb34a0
DM
289sub DESTROY {}; # avoid problems with autoload
290
e143e9d8
DM
291sub AUTOLOAD {
292 my ($this) = @_;
293
294 # also see "man perldiag"
295
296 my $sub = $AUTOLOAD;
297 (my $method = $sub) =~ s/.*:://;
298
e143e9d8
DM
299 my $info = $this->map_method_by_name($method);
300
301 *{$sub} = sub {
302 my $self = shift;
303 return $self->handle($info, @_);
304 };
305 goto &$AUTOLOAD;
306}
307
308sub method_attributes {
309 my ($self) = @_;
310
311 return $method_registry->{$self};
312}
313
314sub map_method_by_name {
315 my ($self, $name) = @_;
316
317 my $info = $method_by_name->{$self}->{$name};
318 die "no such method '${self}::$name'\n" if !$info;
319
320 return $info;
321}
322
c1089794 323sub map_path_to_methods {
39313ced 324 my ($class, $stack, $uri_param, $pathmatchref) = @_;
e143e9d8 325
c1089794 326 my $path_lookup = $method_path_lookup->{$class};
e143e9d8 327
39313ced
DM
328 # Note: $pathmatchref can be used to obtain path including
329 # uri patterns like '/cluster/firewall/groups/{group}'.
330 # Used by pvesh to display help
331 if (defined($pathmatchref)) {
332 $$pathmatchref = '' if !$$pathmatchref;
333 }
334
844a246d 335 while (defined(my $comp = shift @$stack)) {
c1089794
DM
336 return undef if !$path_lookup; # not registerd?
337 if ($path_lookup->{regex}) {
338 my $name = $path_lookup->{regex}->{match_name};
339 my $regex = $path_lookup->{regex}->{match_re};
e143e9d8 340
c1089794
DM
341 return undef if $comp !~ m/^($regex)$/;
342 $uri_param->{$name} = $1;
343 $path_lookup = $path_lookup->{regex};
39313ced 344 $$pathmatchref .= '/{' . $name . '}' if defined($pathmatchref);
c1089794
DM
345 } elsif ($path_lookup->{folders}) {
346 $path_lookup = $path_lookup->{folders}->{$comp};
39313ced 347 $$pathmatchref .= '/' . $comp if defined($pathmatchref);
e143e9d8 348 } else {
c1089794 349 die "internal error";
e143e9d8 350 }
c1089794
DM
351
352 return undef if !$path_lookup;
e143e9d8 353
c1089794
DM
354 if (my $info = $path_lookup->{SUBCLASS}) {
355 $class = $info->{subclass};
e143e9d8 356
c1089794 357 my $fd = $info->{fragmentDelimiter};
e143e9d8 358
c1089794
DM
359 if (defined($fd)) {
360 # we only support the empty string '' (match whole URI)
361 die "unsupported fragmentDelimiter '$fd'"
362 if $fd ne '';
e143e9d8 363
c1089794
DM
364 $stack = [ join ('/', @$stack) ] if scalar(@$stack) > 1;
365 }
366 $path_lookup = $method_path_lookup->{$class};
e143e9d8 367 }
c1089794 368 }
e143e9d8 369
c1089794 370 return undef if !$path_lookup;
e143e9d8 371
c1089794
DM
372 return ($class, $path_lookup);
373}
e143e9d8 374
c1089794 375sub find_handler {
39313ced 376 my ($class, $method, $path, $uri_param, $pathmatchref) = @_;
e143e9d8 377
c1089794 378 my $stack = [ grep { length($_) > 0 } split('\/+' , $path)]; # skip empty fragments
e143e9d8 379
c1089794
DM
380 my ($handler_class, $path_info);
381 eval {
39313ced 382 ($handler_class, $path_info) = $class->map_path_to_methods($stack, $uri_param, $pathmatchref);
c1089794
DM
383 };
384 my $err = $@;
385 syslog('err', $err) if $err;
e143e9d8 386
c1089794 387 return undef if !($handler_class && $path_info);
e143e9d8 388
c1089794 389 my $method_info = $path_info->{$method};
e143e9d8 390
c1089794 391 return undef if !$method_info;
e143e9d8 392
c1089794 393 return ($handler_class, $method_info);
e143e9d8
DM
394}
395
396sub handle {
0adee985 397 my ($self, $info, $param, $output_options) = @_;
e143e9d8
DM
398
399 my $func = $info->{code};
400
401 if (!($info->{name} && $func)) {
402 raise("Method lookup failed ('$info->{name}')\n",
403 code => HTTP_INTERNAL_SERVER_ERROR);
404 }
405
406 if (my $schema = $info->{parameters}) {
407 # warn "validate ". Dumper($param}) . "\n" . Dumper($schema);
408 PVE::JSONSchema::validate($param, $schema);
409 # untaint data (already validated)
5851be88 410 my $extra = delete $param->{'extra-args'};
e143e9d8
DM
411 while (my ($key, $val) = each %$param) {
412 ($param->{$key}) = $val =~ /^(.*)$/s;
413 }
5851be88 414 $param->{'extra-args'} = [map { /^(.*)$/ } @$extra] if $extra;
e143e9d8
DM
415 }
416
0adee985
DM
417 $output_options //= {};
418 my $result = &$func($param, $output_options);
e143e9d8
DM
419
420 # todo: this is only to be safe - disable?
421 if (my $schema = $info->{returns}) {
9030a7d7 422 PVE::JSONSchema::validate($result, $schema, "Result verification failed\n");
e143e9d8
DM
423 }
424
425 return $result;
426}
427
8fa050cd 428# format option, display type and description
921f91d1
DM
429# $name: option name
430# $display_name: for example "-$name" of "<$name>", pass undef to use "$name:"
8fa050cd 431# $phash: json schema property hash
b0e5e9fa 432# $format: 'asciidoc', 'short', 'long' or 'full'
abc1afd8 433# $style: 'config', 'config-sub', 'arg' or 'fixed'
dfc6cff8 434# $mapdef: parameter mapping ({ desc => XXX, func => sub {...} })
8fa050cd 435my $get_property_description = sub {
4842b651 436 my ($name, $style, $phash, $format, $mapdef) = @_;
8fa050cd
DM
437
438 my $res = '';
439
440 $format = 'asciidoc' if !defined($format);
441
442 my $descr = $phash->{description} || "no description available";
443
32f8e0c7
DM
444 if ($phash->{verbose_description} &&
445 ($style eq 'config' || $style eq 'config-sub')) {
446 $descr = $phash->{verbose_description};
447 }
448
8fa050cd
DM
449 chomp $descr;
450
77096a6f 451 my $type_text = PVE::JSONSchema::schema_get_type_text($phash, $style);
8fa050cd 452
dfc6cff8
DM
453 if ($mapdef && $phash->{type} eq 'string') {
454 $type_text = $mapdef->{desc};
4845032a
FG
455 }
456
8fa050cd
DM
457 if ($format eq 'asciidoc') {
458
df79b428 459 if ($style eq 'config') {
921f91d1 460 $res .= "`$name`: ";
32f8e0c7
DM
461 } elsif ($style eq 'config-sub') {
462 $res .= "`$name`=";
df79b428 463 } elsif ($style eq 'arg') {
a4f181a3 464 $res .= "`--$name` ";
df79b428 465 } elsif ($style eq 'fixed') {
abc1afd8 466 $res .= "`<$name>`: ";
df79b428
DM
467 } else {
468 die "unknown style '$style'";
8fa050cd
DM
469 }
470
77096a6f 471 $res .= "`$type_text` " if $type_text;
8fa050cd
DM
472
473 if (defined(my $dv = $phash->{default})) {
25d9bda9 474 $res .= "('default =' `$dv`)";
8fa050cd 475 }
a736ac99 476
32f8e0c7
DM
477 if ($style eq 'config-sub') {
478 $res .= ";;\n\n";
479 } else {
480 $res .= "::\n\n";
481 }
482
483 my $wdescr = $descr;
a736ac99
DM
484 chomp $wdescr;
485 $wdescr =~ s/^$/+/mg;
486
487 $res .= $wdescr . "\n";
8fa050cd
DM
488
489 if (my $req = $phash->{requires}) {
490 my $tmp .= ref($req) ? join(', ', @$req) : $req;
491 $res .= "+\nNOTE: Requires option(s): `$tmp`\n";
492 }
493 $res .= "\n";
494
b0e5e9fa 495 } elsif ($format eq 'short' || $format eq 'long' || $format eq 'full') {
8fa050cd
DM
496
497 my $defaulttxt = '';
498 if (defined(my $dv = $phash->{default})) {
499 $defaulttxt = " (default=$dv)";
500 }
501
df79b428
DM
502 my $display_name;
503 if ($style eq 'config') {
504 $display_name = "$name:";
505 } elsif ($style eq 'arg') {
506 $display_name = "-$name";
507 } elsif ($style eq 'fixed') {
508 $display_name = "<$name>";
509 } else {
510 die "unknown style '$style'";
511 }
8fa050cd 512
77096a6f 513 my $tmp = sprintf " %-10s %s$defaulttxt\n", $display_name, "$type_text";
8fa050cd
DM
514 my $indend = " ";
515
516 $res .= Text::Wrap::wrap('', $indend, ($tmp));
517 $res .= "\n",
518 $res .= Text::Wrap::wrap($indend, $indend, ($descr)) . "\n\n";
519
520 if (my $req = $phash->{requires}) {
521 my $tmp = "Requires option(s): ";
522 $tmp .= ref($req) ? join(', ', @$req) : $req;
523 $res .= Text::Wrap::wrap($indend, $indend, ($tmp)). "\n\n";
524 }
525
526 } else {
527 die "unknown format '$format'";
528 }
529
530 return $res;
531};
532
dfc6cff8
DM
533# translate parameter mapping definition
534# $mapping_array is a array which can contain:
535# strings ... in that case we assume it is a parameter name, and
536# we want to load that parameter from a file
537# [ param_name, func, desc] ... allows you to specify a arbitrary
538# mapping func for any param
539#
540# Returns: a hash indexed by parameter_name,
541# i.e. { param_name => { func => .., desc => ... } }
542my $compute_param_mapping_hash = sub {
543 my ($mapping_array) = @_;
544
545 my $res = {};
546
547 return $res if !defined($mapping_array);
548
549 foreach my $item (@$mapping_array) {
c7171ff2 550 my ($name, $func, $desc, $interactive);
dfc6cff8 551 if (ref($item) eq 'ARRAY') {
c7171ff2 552 ($name, $func, $desc, $interactive) = @$item;
a1c7edda
DC
553 } elsif (ref($item) eq 'HASH') {
554 # just use the hash
555 $res->{$item->{name}} = $item;
556 next;
dfc6cff8
DM
557 } else {
558 $name = $item;
559 $func = sub { return PVE::Tools::file_get_contents($_[0]) };
560 }
561 $desc //= '<filepath>';
c7171ff2 562 $res->{$name} = { desc => $desc, func => $func, interactive => $interactive };
dfc6cff8
DM
563 }
564
565 return $res;
566};
567
e143e9d8
DM
568# generate usage information for command line tools
569#
c03b7509 570# $info ... method info
e143e9d8 571# $prefix ... usually something like "$exename $cmd" ('pvesm add')
1d21344c
DM
572# $arg_param ... list of parameters we want to get as ordered arguments
573# on the command line (or single parameter name for lists)
e143e9d8
DM
574# $fixed_param ... do not generate and info about those parameters
575# $format:
b0e5e9fa
DM
576# 'long' ... default (text, list all options)
577# 'short' ... command line only (text, one line)
578# 'full' ... text, include description
fe3f1fde 579# 'asciidoc' ... generate asciidoc for man pages (like 'full')
968bcf45 580# $param_cb ... mapping for string parameters to file path parameters
c03b7509
DM
581sub getopt_usage {
582 my ($info, $prefix, $arg_param, $fixed_param, $format, $param_cb) = @_;
e143e9d8
DM
583
584 $format = 'long' if !$format;
585
e143e9d8 586 my $schema = $info->{parameters};
c03b7509 587 my $name = $info->{name};
e143e9d8
DM
588 my $prop = $schema->{properties};
589
590 my $out = '';
591
592 my $arg_hash = {};
593
594 my $args = '';
1d21344c
DM
595
596 $arg_param = [ $arg_param ] if $arg_param && !ref($arg_param);
597
e143e9d8
DM
598 foreach my $p (@$arg_param) {
599 next if !$prop->{$p}; # just to be sure
1d21344c 600 my $pd = $prop->{$p};
e143e9d8
DM
601
602 $arg_hash->{$p} = 1;
603 $args .= " " if $args;
1d21344c 604 if ($pd->{format} && $pd->{format} =~ m/-list/) {
7f0f0610 605 $args .= "{<$p>}";
1d21344c
DM
606 } else {
607 $args .= $pd->{optional} ? "[<$p>]" : "<$p>";
608 }
e143e9d8
DM
609 }
610
e143e9d8
DM
611 my $argdescr = '';
612 foreach my $k (@$arg_param) {
613 next if defined($fixed_param->{$k}); # just to be sure
614 next if !$prop->{$k}; # just to be sure
4842b651 615 $argdescr .= $get_property_description->($k, 'fixed', $prop->{$k}, $format);
e143e9d8
DM
616 }
617
618 my $idx_param = {}; # -vlan\d+ -scsi\d+
619
620 my $opts = '';
621 foreach my $k (sort keys %$prop) {
622 next if $arg_hash->{$k};
623 next if defined($fixed_param->{$k});
624
77096a6f 625 my $type_text = $prop->{$k}->{type} || 'string';
e143e9d8 626
968bcf45 627 my $param_map = {};
4842b651 628
968bcf45
TL
629 if (defined($param_cb)) {
630 my $mapping = $param_cb->($name);
631 $param_map = $compute_param_mapping_hash->($mapping);
632 next if $k eq 'password' && $param_map->{$k} && !$prop->{$k}->{optional};
4842b651 633 }
e143e9d8
DM
634
635 my $base = $k;
636 if ($k =~ m/^([a-z]+)(\d+)$/) {
b546f33e 637 my ($name, $idx) = ($1, $2);
e143e9d8 638 next if $idx_param->{$name};
b54ad320 639 if ($idx == 0 && defined($prop->{"${name}1"})) {
f922b8a8
FG
640 $idx_param->{$name} = 1;
641 $base = "${name}[n]";
642 }
e143e9d8
DM
643 }
644
dfc6cff8 645
968bcf45 646 $opts .= $get_property_description->($base, 'arg', $prop->{$k}, $format, $param_map->{$k});
e143e9d8
DM
647
648 if (!$prop->{$k}->{optional}) {
649 $args .= " " if $args;
a4f181a3 650 $args .= "--$base <$type_text>"
e143e9d8
DM
651 }
652 }
653
fe3f1fde
DM
654 if ($format eq 'asciidoc') {
655 $out .= "*${prefix}*";
656 $out .= " `$args`" if $args;
657 $out .= $opts ? " `[OPTIONS]`\n" : "\n";
658 } else {
659 $out .= "USAGE: " if $format ne 'short';
660 $out .= "$prefix $args";
661 $out .= $opts ? " [OPTIONS]\n" : "\n";
662 }
e143e9d8
DM
663
664 return $out if $format eq 'short';
665
fe3f1fde
DM
666 if ($info->{description}) {
667 if ($format eq 'asciidoc') {
668 my $desc = Text::Wrap::wrap('', '', ($info->{description}));
669 $out .= "\n$desc\n\n";
670 } elsif ($format eq 'full') {
671 my $desc = Text::Wrap::wrap(' ', ' ', ($info->{description}));
672 $out .= "\n$desc\n\n";
673 }
e143e9d8
DM
674 }
675
676 $out .= $argdescr if $argdescr;
677
678 $out .= $opts if $opts;
679
680 return $out;
681}
682
c03b7509
DM
683sub usage_str {
684 my ($self, $name, $prefix, $arg_param, $fixed_param, $format, $param_cb) = @_;
685
686 my $info = $self->map_method_by_name($name);
687
688 return getopt_usage($info, $prefix, $arg_param, $fixed_param, $format, $param_cb);
689}
690
8fa050cd
DM
691# generate docs from JSON schema properties
692sub dump_properties {
df79b428 693 my ($prop, $format, $style, $filterFn) = @_;
8fa050cd
DM
694
695 my $raw = '';
696
df79b428
DM
697 $style //= 'config';
698
8fa050cd
DM
699 my $idx_param = {}; # -vlan\d+ -scsi\d+
700
701 foreach my $k (sort keys %$prop) {
702 my $phash = $prop->{$k};
703
704 next if defined($filterFn) && &$filterFn($k, $phash);
32f8e0c7 705 next if $phash->{alias};
8fa050cd
DM
706
707 my $base = $k;
708 if ($k =~ m/^([a-z]+)(\d+)$/) {
b546f33e 709 my ($name, $idx) = ($1, $2);
8fa050cd 710 next if $idx_param->{$name};
b54ad320 711 if ($idx == 0 && defined($prop->{"${name}1"})) {
f922b8a8
FG
712 $idx_param->{$name} = 1;
713 $base = "${name}[n]";
714 }
8fa050cd
DM
715 }
716
4842b651 717 $raw .= $get_property_description->($base, $style, $phash, $format);
32f8e0c7
DM
718
719 next if $style ne 'config';
720
721 my $prop_fmt = $phash->{format};
722 next if !$prop_fmt;
723
724 if (ref($prop_fmt) ne 'HASH') {
725 $prop_fmt = PVE::JSONSchema::get_format($prop_fmt);
726 }
727
728 next if !(ref($prop_fmt) && (ref($prop_fmt) eq 'HASH'));
729
730 $raw .= dump_properties($prop_fmt, $format, 'config-sub')
731
8fa050cd 732 }
b0e5e9fa 733
8fa050cd
DM
734 return $raw;
735}
736
408976c6 737my $replace_file_names_with_contents = sub {
968bcf45 738 my ($param, $param_map) = @_;
408976c6 739
968bcf45 740 while (my ($k, $d) = each %$param_map) {
c7171ff2 741 next if $d->{interactive}; # handled by the JSONSchema's get_options code
dfc6cff8
DM
742 $param->{$k} = $d->{func}->($param->{$k})
743 if defined($param->{$k});
408976c6
FG
744 }
745
746 return $param;
747};
748
0adee985
DM
749our $standard_output_options = {
750 format => PVE::JSONSchema::get_standard_option('pve-output-format'),
751 noheader => {
752 description => "Do not show column headers (for 'text' format).",
753 type => 'boolean',
754 optional => 1,
755 default => 1,
756 },
757 noborder => {
758 description => "Do not draw borders (for 'text' format).",
759 type => 'boolean',
760 optional => 1,
761 default => 1,
762 },
763 quiet => {
764 description => "Suppress printing results.",
765 type => 'boolean',
766 optional => 1,
767 },
768 'human-readable' => {
769 description => "Call output rendering functions to produce human readable text.",
770 type => 'boolean',
771 optional => 1,
772 default => 1,
773 }
774};
775
776sub add_standard_output_parameters {
777 my ($org_schema) = @_;
778
779 my $schema = { %$org_schema };
780 $schema->{properties} = { %{$schema->{properties}}, %$standard_output_options };
781
782 return $schema;
783};
784
e143e9d8 785sub cli_handler {
0adee985 786 my ($self, $prefix, $name, $args, $arg_param, $fixed_param, $param_cb, $options) = @_;
e143e9d8
DM
787
788 my $info = $self->map_method_by_name($name);
0adee985 789 $options //= {};
e143e9d8 790
e143e9d8
DM
791 my $res;
792 eval {
968bcf45
TL
793 my $param_map = {};
794 $param_map = $compute_param_mapping_hash->($param_cb->($name)) if $param_cb;
0adee985
DM
795 my $schema = add_standard_output_parameters($info->{parameters});
796 my $param = PVE::JSONSchema::get_options($schema, $args, $arg_param, $fixed_param, $param_map);
797
798 foreach my $opt (keys %$standard_output_options) {
799 $options->{$opt} = delete $param->{$opt} if defined($param->{$opt});
800 }
dfc6cff8 801
968bcf45
TL
802 if (defined($param_map)) {
803 $replace_file_names_with_contents->($param, $param_map);
dfc6cff8
DM
804 }
805
0adee985 806 $res = $self->handle($info, $param, $options);
e143e9d8
DM
807 };
808 if (my $err = $@) {
809 my $ec = ref($err);
810
811 die $err if !$ec || $ec ne "PVE::Exception" || !$err->is_param_exc();
812
968bcf45 813 $err->{usage} = $self->usage_str($name, $prefix, $arg_param, $fixed_param, 'short', $param_cb);
e143e9d8
DM
814
815 die $err;
816 }
817
818 return $res;
819}
820
821# utility methods
822# note: this modifies the original hash by adding the id property
823sub hash_to_array {
824 my ($hash, $idprop) = @_;
825
826 my $res = [];
827 return $res if !$hash;
828
829 foreach my $k (keys %$hash) {
830 $hash->{$k}->{$idprop} = $k;
831 push @$res, $hash->{$k};
832 }
833
834 return $res;
835}
836
8371;