]> git.proxmox.com Git - pve-common.git/blame_incremental - src/PVE/RESTHandler.pm
REST handler: get property description: escape curly braces for asciidoc
[pve-common.git] / src / PVE / RESTHandler.pm
... / ...
CommitLineData
1package PVE::RESTHandler;
2
3use strict;
4no strict 'refs'; # our autoload requires this
5use warnings;
6use PVE::SafeSyslog;
7use PVE::Exception qw(raise raise_param_exc);
8use PVE::JSONSchema;
9use PVE::Tools;
10use HTTP::Status qw(:constants :is status_message);
11use Text::Wrap;
12use Clone qw(clone);
13
14my $method_registry = {};
15my $method_by_name = {};
16my $method_path_lookup = {};
17
18our $AUTOLOAD; # it's a package global
19
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,
26 default => 0,
27 },
28 noborder => {
29 description => "Do not draw borders (for 'text' format).",
30 type => 'boolean',
31 optional => 1,
32 default => 0,
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
47sub api_clone_schema {
48 my ($schema, $no_typetext) = @_;
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') {
57 $res->{$k} = ref($d) ? clone($d) : $d;
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+)$/) {
64 my ($name, $idx) = ($1, $2);
65 if ($idx == 0 && defined($d->{"${name}1"})) {
66 $p = "${name}[n]";
67 } elsif ($idx > 0 && defined($d->{"${name}0"})) {
68 next; # only handle once for -xx0, but only if -xx0 exists
69 }
70 }
71 my $tmp = ref($pd) ? clone($pd) : $pd;
72 # NOTE: add typetext property for complexer types, to make the web api-viewer code simpler
73 if (!$no_typetext && !(defined($tmp->{enum}) || defined($tmp->{pattern}))) {
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;
80 }
81 }
82
83 return $res;
84}
85
86sub api_dump_full {
87 my ($tree, $index, $class, $prefix, $raw_dump) = @_;
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}) {
99 api_dump_full($tree, $index, $info->{subclass}, $path, $raw_dump);
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};
139
140 if ($raw_dump) {
141 $data->{$k} = $d;
142 } else {
143 if ($k eq 'parameters') {
144 $data->{$k} = api_clone_schema($d);
145 } elsif ($k eq 'returns') {
146 $data->{$k} = api_clone_schema($d, 1);
147 } else {
148 $data->{$k} = ref($d) ? clone($d) : $d;
149 }
150 }
151 }
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
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
206sub api_dump {
207 my ($class, $prefix, $raw_dump) = @_;
208
209 my $tree = [];
210
211 my $index = {};
212 api_dump_full($tree, $index, $class, $prefix, $raw_dump);
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
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};
244
245 # apply default value
246 $info->{allowtoken} = 1 if !defined($info->{allowtoken});
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});
253
254 foreach my $comp (split(/\/+/, $info->{path})) {
255 die "$errprefix path compoment has zero length\n" if $comp eq '';
256 my ($name, $regex);
257 if ($comp =~ m/^\{([\w-]+)(?::(.*))?\}$/) {
258 $name = $1;
259 $regex = $2 ? $2 : '\S+';
260 push @$match_re, $regex;
261 push @$match_name, $name;
262 } else {
263 $name = $comp;
264 push @$match_re, $name;
265 push @$match_name, undef;
266 }
267
268 if ($regex) {
269 $path_lookup->{regex} = {} if !defined($path_lookup->{regex});
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;
279
280 die "$errprefix path match error - regex and fixed items\n"
281 if defined($path_lookup->{folders});
282
283 $path_lookup = $path_lookup->{regex};
284
285 } else {
286 $path_lookup->{folders}->{$name} = {} if !defined($path_lookup->{folders}->{$name});
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};
292 }
293 }
294
295 die "$errprefix duplicate method definition\n"
296 if defined($path_lookup->{$method});
297
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 }
303 $path_lookup->{$method} = $info;
304
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}) {
311 die "$errprefix method name already defined\n"
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
320sub DESTROY {}; # avoid problems with autoload
321
322sub AUTOLOAD {
323 my ($this) = @_;
324
325 # also see "man perldiag"
326
327 my $sub = $AUTOLOAD;
328 (my $method = $sub) =~ s/.*:://;
329
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
354sub map_path_to_methods {
355 my ($class, $stack, $uri_param, $pathmatchref) = @_;
356
357 my $path_lookup = $method_path_lookup->{$class};
358
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
366 while (defined(my $comp = shift @$stack)) {
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};
371
372 return undef if $comp !~ m/^($regex)$/;
373 $uri_param->{$name} = $1;
374 $path_lookup = $path_lookup->{regex};
375 $$pathmatchref .= '/{' . $name . '}' if defined($pathmatchref);
376 } elsif ($path_lookup->{folders}) {
377 $path_lookup = $path_lookup->{folders}->{$comp};
378 $$pathmatchref .= '/' . $comp if defined($pathmatchref);
379 } else {
380 die "internal error";
381 }
382
383 return undef if !$path_lookup;
384
385 if (my $info = $path_lookup->{SUBCLASS}) {
386 $class = $info->{subclass};
387
388 my $fd = $info->{fragmentDelimiter};
389
390 if (defined($fd)) {
391 # we only support the empty string '' (match whole URI)
392 die "unsupported fragmentDelimiter '$fd'"
393 if $fd ne '';
394
395 $stack = [ join ('/', @$stack) ] if scalar(@$stack) > 1;
396 }
397 $path_lookup = $method_path_lookup->{$class};
398 }
399 }
400
401 return undef if !$path_lookup;
402
403 return ($class, $path_lookup);
404}
405
406sub find_handler {
407 my ($class, $method, $path, $uri_param, $pathmatchref) = @_;
408
409 my $stack = [ grep { length($_) > 0 } split('\/+' , $path)]; # skip empty fragments
410
411 my ($handler_class, $path_info);
412 eval {
413 ($handler_class, $path_info) = $class->map_path_to_methods($stack, $uri_param, $pathmatchref);
414 };
415 my $err = $@;
416 syslog('err', $err) if $err;
417
418 return undef if !($handler_class && $path_info);
419
420 my $method_info = $path_info->{$method};
421
422 return undef if !$method_info;
423
424 return ($handler_class, $method_info);
425}
426
427sub handle {
428 my ($self, $info, $param, $result_verification) = @_;
429
430 my $func = $info->{code};
431
432 if (!($info->{name} && $func)) {
433 raise("Method lookup failed ('$info->{name}')\n", code => HTTP_INTERNAL_SERVER_ERROR);
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)
440 my $extra = delete $param->{'extra-args'};
441 while (my ($key, $val) = each %$param) {
442 if (defined($val)) {
443 ($param->{$key}) = $val =~ /^(.*)$/s;
444 } else {
445 $param->{$key} = undef;
446 }
447 }
448 $param->{'extra-args'} = [map { /^(.*)$/ } @$extra] if $extra;
449 }
450
451 my $result = $func->($param); # the actual API code execution call
452
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.
456 PVE::JSONSchema::validate($result, $schema, "Result verification failed\n");
457 }
458 return $result;
459}
460
461# format option, display type and description
462# $name: option name
463# $display_name: for example "-$name" of "<$name>", pass undef to use "$name:"
464# $phash: json schema property hash
465# $format: 'asciidoc', 'short', 'long' or 'full'
466# $style: 'config', 'config-sub', 'arg' or 'fixed'
467# $mapdef: parameter mapping ({ desc => XXX, func => sub {...} })
468my $get_property_description = sub {
469 my ($name, $style, $phash, $format, $mapdef) = @_;
470
471 my $res = '';
472
473 $format = 'asciidoc' if !defined($format);
474
475 my $descr = $phash->{description} || "no description available";
476
477 if ($phash->{verbose_description} &&
478 ($style eq 'config' || $style eq 'config-sub')) {
479 $descr = $phash->{verbose_description};
480 }
481
482 chomp $descr;
483
484 my $type_text = PVE::JSONSchema::schema_get_type_text($phash, $style);
485
486 if ($mapdef && $phash->{type} eq 'string') {
487 $type_text = $mapdef->{desc};
488 }
489
490 if ($format eq 'asciidoc') {
491
492 if ($style eq 'config') {
493 $res .= "`$name`: ";
494 } elsif ($style eq 'config-sub') {
495 $res .= "`$name`=";
496 } elsif ($style eq 'arg') {
497 $res .= "`--$name` ";
498 } elsif ($style eq 'fixed') {
499 $res .= "`<$name>`: ";
500 } else {
501 die "unknown style '$style'";
502 }
503
504 $res .= "`$type_text` " if $type_text;
505
506 if (defined(my $dv = $phash->{default})) {
507 $res .= "('default =' `$dv`)";
508 }
509
510 if ($style eq 'config-sub') {
511 $res .= ";;\n\n";
512 } else {
513 $res .= "::\n\n";
514 }
515
516 my $wdescr = $descr;
517 chomp $wdescr;
518 $wdescr =~ s/^$/+/mg;
519
520 $wdescr =~ s/{/\\{/g;
521 $wdescr =~ s/}/\\}/g;
522
523 $res .= $wdescr . "\n";
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
531 } elsif ($format eq 'short' || $format eq 'long' || $format eq 'full') {
532
533 my $defaulttxt = '';
534 if (defined(my $dv = $phash->{default})) {
535 $defaulttxt = " (default=$dv)";
536 }
537
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 }
548
549 my $tmp = sprintf " %-10s %s%s\n", $display_name, "$type_text", "$defaulttxt";
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
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) {
586 my ($name, $func, $desc, $interactive);
587 if (ref($item) eq 'ARRAY') {
588 ($name, $func, $desc, $interactive) = @$item;
589 } elsif (ref($item) eq 'HASH') {
590 # just use the hash
591 $res->{$item->{name}} = $item;
592 next;
593 } else {
594 $name = $item;
595 $func = sub { return PVE::Tools::file_get_contents($_[0]) };
596 }
597 $desc //= '<filepath>';
598 $res->{$name} = { desc => $desc, func => $func, interactive => $interactive };
599 }
600
601 return $res;
602};
603
604# generate usage information for command line tools
605#
606# $info ... method info
607# $prefix ... usually something like "$exename $cmd" ('pvesm add')
608# $arg_param ... list of parameters we want to get as ordered arguments
609# on the command line (or single parameter name for lists)
610# $fixed_param ... do not generate and info about those parameters
611# $format:
612# 'long' ... default (text, list all options)
613# 'short' ... command line only (text, one line)
614# 'full' ... text, include description
615# 'asciidoc' ... generate asciidoc for man pages (like 'full')
616# $param_cb ... mapping for string parameters to file path parameters
617# $formatter_properties ... additional property definitions (passed to output formatter)
618sub getopt_usage {
619 my ($info, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties) = @_;
620
621 $format = 'long' if !$format;
622
623 my $schema = $info->{parameters};
624 my $name = $info->{name};
625 my $prop = {};
626 if ($schema->{properties}) {
627 $prop = { %{$schema->{properties}} }; # copy
628 }
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 }
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 }
647 }
648 }
649
650 my $out = '';
651
652 my $arg_hash = {};
653
654 my $args = '';
655
656 $arg_param = [ $arg_param ] if $arg_param && !ref($arg_param);
657
658 foreach my $p (@$arg_param) {
659 next if !$prop->{$p}; # just to be sure
660 my $pd = $prop->{$p};
661
662 $arg_hash->{$p} = 1;
663 $args .= " " if $args;
664 if ($pd->{format} && $pd->{format} =~ m/-list/) {
665 $args .= "{<$p>}";
666 } else {
667 $args .= $pd->{optional} ? "[<$p>]" : "<$p>";
668 }
669 }
670
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
675 $argdescr .= $get_property_description->($k, 'fixed', $prop->{$k}, $format);
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
685 my $type_text = $prop->{$k}->{type} || 'string';
686
687 my $param_map = {};
688
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};
693 }
694
695 my $base = $k;
696 if ($k =~ m/^([a-z]+)(\d+)$/) {
697 my ($name, $idx) = ($1, $2);
698 next if $idx_param->{$name};
699 if ($idx == 0 && defined($prop->{"${name}1"})) {
700 $idx_param->{$name} = 1;
701 $base = "${name}[n]";
702 }
703 }
704
705
706 $opts .= $get_property_description->($base, 'arg', $prop->{$k}, $format, $param_map->{$k});
707
708 if (!$prop->{$k}->{optional}) {
709 $args .= " " if $args;
710 $args .= "--$base <$type_text>"
711 }
712 }
713
714 if ($format eq 'asciidoc') {
715 $out .= "*${prefix}*";
716 $out .= " `$args`" if $args;
717 $out .= " `[OPTIONS]`" if $opts;
718 $out .= " `[FORMAT_OPTIONS]`" if $has_output_format_option;
719 $out .= "\n";
720 } else {
721 $out .= "USAGE: " if $format ne 'short';
722 $out .= "$prefix $args";
723 $out .= " [OPTIONS]" if $opts;
724 $out .= " [FORMAT_OPTIONS]" if $has_output_format_option;
725 $out .= "\n";
726 }
727
728 return $out if $format eq 'short';
729
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 }
738 }
739
740 $out .= $argdescr if $argdescr;
741
742 $out .= $opts if $opts;
743
744 return $out;
745}
746
747sub usage_str {
748 my ($self, $name, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties) = @_;
749
750 my $info = $self->map_method_by_name($name);
751
752 return getopt_usage($info, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties);
753}
754
755# generate docs from JSON schema properties
756sub dump_properties {
757 my ($prop, $format, $style, $filterFn) = @_;
758
759 my $raw = '';
760
761 $style //= 'config';
762
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);
769 next if $phash->{alias};
770
771 my $base = $k;
772 if ($k =~ m/^([a-z]+)(\d+)$/) {
773 my ($name, $idx) = ($1, $2);
774 next if $idx_param->{$name};
775 if ($idx == 0 && defined($prop->{"${name}1"})) {
776 $idx_param->{$name} = 1;
777 $base = "${name}[n]";
778 }
779 }
780
781 $raw .= $get_property_description->($base, $style, $phash, $format);
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')
795
796 }
797
798 return $raw;
799}
800
801my $replace_file_names_with_contents = sub {
802 my ($param, $param_map) = @_;
803
804 while (my ($k, $d) = each %$param_map) {
805 next if $d->{interactive}; # handled by the JSONSchema's get_options code
806 $param->{$k} = $d->{func}->($param->{$k})
807 if defined($param->{$k});
808 }
809
810 return $param;
811};
812
813sub add_standard_output_properties {
814 my ($propdef, $list) = @_;
815
816 $propdef //= {};
817
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}
841
842sub cli_handler {
843 my ($self, $prefix, $name, $args, $arg_param, $fixed_param, $param_cb, $formatter_properties) = @_;
844
845 my $info = $self->map_method_by_name($name);
846 my $res;
847 my $fmt_param = {};
848
849 eval {
850 my $param_map = {};
851 $param_map = $compute_param_mapping_hash->($param_cb->($name)) if $param_cb;
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 }
861
862 if (defined($param_map)) {
863 $replace_file_names_with_contents->($param, $param_map);
864 }
865
866 $res = $self->handle($info, $param, 1);
867 };
868 if (my $err = $@) {
869 my $ec = ref($err);
870
871 die $err if !$ec || $ec ne "PVE::Exception" || !$err->is_param_exc();
872
873 $err->{usage} = $self->usage_str($name, $prefix, $arg_param, $fixed_param, 'short', $param_cb, $formatter_properties);
874
875 die $err;
876 }
877
878 return wantarray ? ($res, $fmt_param) : $res;
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;