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