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