]> git.proxmox.com Git - pve-client.git/blob - PVE/APIClient/RESTHandler.pm
fixes for changes in pve-common
[pve-client.git] / PVE / APIClient / RESTHandler.pm
1 package PVE::APIClient::RESTHandler;
2
3 use strict;
4 no strict 'refs'; # our autoload requires this
5 use warnings;
6 use PVE::APIClient::SafeSyslog;
7 use PVE::APIClient::Exception qw(raise raise_param_exc);
8 use PVE::APIClient::JSONSchema;
9 use PVE::APIClient::Tools;
10 use HTTP::Status qw(:constants :is status_message);
11 use Text::Wrap;
12 use Clone qw(clone);
13
14 my $method_registry = {};
15 my $method_by_name = {};
16 my $method_path_lookup = {};
17
18 our $AUTOLOAD; # it's a package global
19
20 sub 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') {
30 $res->{$k} = ref($d) ? clone($d) : $d;
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+)$/) {
37 my ($name, $idx) = ($1, $2);
38 if ($idx == 0 && defined($d->{"${name}1"})) {
39 $p = "${name}[n]";
40 } elsif ($idx > 0 && defined($d->{"${name}0"})) {
41 next; # only handle once for -xx0, but only if -xx0 exists
42 }
43 }
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::APIClient::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;
54 }
55 }
56
57 return $res;
58 }
59
60 sub api_dump_full {
61 my ($tree, $index, $class, $prefix, $raw_dump) = @_;
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}) {
73 api_dump_full($tree, $index, $info->{subclass}, $path, $raw_dump);
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};
113
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 }
122 }
123 }
124 $res->{info}->{$info->{method}} = $data;
125 };
126 }
127 }
128 };
129
130 sub 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
145 # api_dump_remove_refs: prepare API tree for use with to_json($tree)
146 sub 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
178 sub api_dump {
179 my ($class, $prefix, $raw_dump) = @_;
180
181 my $tree = [];
182
183 my $index = {};
184 api_dump_full($tree, $index, $class, $prefix, $raw_dump);
185 api_dump_cleanup_tree($tree);
186 return $tree;
187 };
188
189 sub 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::APIClient::JSONSchema::validate_method_info($info);
196 }
197 }
198 }
199
200 sub register_method {
201 my ($self, $info) = @_;
202
203 my $match_re = [];
204 my $match_name = [];
205
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
223 foreach my $comp (split(/\/+/, $info->{path})) {
224 die "$errprefix path compoment has zero length\n" if $comp eq '';
225 my ($name, $regex);
226 if ($comp =~ m/^\{(\w+)(:(.*))?\}$/) {
227 $name = $1;
228 $regex = $3 ? $3 : '\S+';
229 push @$match_re, $regex;
230 push @$match_name, $name;
231 } else {
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};
261 }
262 }
263
264 die "$errprefix duplicate method definition\n"
265 if defined($path_lookup->{$method});
266
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 }
272 $path_lookup->{$method} = $info;
273
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}) {
280 die "$errprefix method name already defined\n"
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
289 sub DESTROY {}; # avoid problems with autoload
290
291 sub AUTOLOAD {
292 my ($this) = @_;
293
294 # also see "man perldiag"
295
296 my $sub = $AUTOLOAD;
297 (my $method = $sub) =~ s/.*:://;
298
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
308 sub method_attributes {
309 my ($self) = @_;
310
311 return $method_registry->{$self};
312 }
313
314 sub 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
323 sub map_path_to_methods {
324 my ($class, $stack, $uri_param, $pathmatchref) = @_;
325
326 my $path_lookup = $method_path_lookup->{$class};
327
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
335 while (defined(my $comp = shift @$stack)) {
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};
340
341 return undef if $comp !~ m/^($regex)$/;
342 $uri_param->{$name} = $1;
343 $path_lookup = $path_lookup->{regex};
344 $$pathmatchref .= '/{' . $name . '}' if defined($pathmatchref);
345 } elsif ($path_lookup->{folders}) {
346 $path_lookup = $path_lookup->{folders}->{$comp};
347 $$pathmatchref .= '/' . $comp if defined($pathmatchref);
348 } else {
349 die "internal error";
350 }
351
352 return undef if !$path_lookup;
353
354 if (my $info = $path_lookup->{SUBCLASS}) {
355 $class = $info->{subclass};
356
357 my $fd = $info->{fragmentDelimiter};
358
359 if (defined($fd)) {
360 # we only support the empty string '' (match whole URI)
361 die "unsupported fragmentDelimiter '$fd'"
362 if $fd ne '';
363
364 $stack = [ join ('/', @$stack) ] if scalar(@$stack) > 1;
365 }
366 $path_lookup = $method_path_lookup->{$class};
367 }
368 }
369
370 return undef if !$path_lookup;
371
372 return ($class, $path_lookup);
373 }
374
375 sub find_handler {
376 my ($class, $method, $path, $uri_param, $pathmatchref) = @_;
377
378 my $stack = [ grep { length($_) > 0 } split('\/+' , $path)]; # skip empty fragments
379
380 my ($handler_class, $path_info);
381 eval {
382 ($handler_class, $path_info) = $class->map_path_to_methods($stack, $uri_param, $pathmatchref);
383 };
384 my $err = $@;
385 syslog('err', $err) if $err;
386
387 return undef if !($handler_class && $path_info);
388
389 my $method_info = $path_info->{$method};
390
391 return undef if !$method_info;
392
393 return ($handler_class, $method_info);
394 }
395
396 sub handle {
397 my ($self, $info, $param) = @_;
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::APIClient::JSONSchema::validate($param, $schema);
409 # untaint data (already validated)
410 my $extra = delete $param->{'extra-args'};
411 while (my ($key, $val) = each %$param) {
412 ($param->{$key}) = $val =~ /^(.*)$/s;
413 }
414 $param->{'extra-args'} = [map { /^(.*)$/ } @$extra] if $extra;
415 }
416
417 my $result = &$func($param);
418
419 # todo: this is only to be safe - disable?
420 if (my $schema = $info->{returns}) {
421 PVE::APIClient::JSONSchema::validate($result, $schema, "Result verification failed\n");
422 }
423
424 return $result;
425 }
426
427 # format option, display type and description
428 # $name: option name
429 # $display_name: for example "-$name" of "<$name>", pass undef to use "$name:"
430 # $phash: json schema property hash
431 # $format: 'asciidoc', 'short', 'long' or 'full'
432 # $style: 'config', 'config-sub', 'arg' or 'fixed'
433 # $mapdef: parameter mapping ({ desc => XXX, func => sub {...} })
434 my $get_property_description = sub {
435 my ($name, $style, $phash, $format, $mapdef) = @_;
436
437 my $res = '';
438
439 $format = 'asciidoc' if !defined($format);
440
441 my $descr = $phash->{description} || "no description available";
442
443 if ($phash->{verbose_description} &&
444 ($style eq 'config' || $style eq 'config-sub')) {
445 $descr = $phash->{verbose_description};
446 }
447
448 chomp $descr;
449
450 my $type_text = PVE::APIClient::JSONSchema::schema_get_type_text($phash, $style);
451
452 if ($mapdef && $phash->{type} eq 'string') {
453 $type_text = $mapdef->{desc};
454 }
455
456 if ($format eq 'asciidoc') {
457
458 if ($style eq 'config') {
459 $res .= "`$name`: ";
460 } elsif ($style eq 'config-sub') {
461 $res .= "`$name`=";
462 } elsif ($style eq 'arg') {
463 $res .= "`--$name` ";
464 } elsif ($style eq 'fixed') {
465 $res .= "`<$name>`: ";
466 } else {
467 die "unknown style '$style'";
468 }
469
470 $res .= "`$type_text` " if $type_text;
471
472 if (defined(my $dv = $phash->{default})) {
473 $res .= "('default =' `$dv`)";
474 }
475
476 if ($style eq 'config-sub') {
477 $res .= ";;\n\n";
478 } else {
479 $res .= "::\n\n";
480 }
481
482 my $wdescr = $descr;
483 chomp $wdescr;
484 $wdescr =~ s/^$/+/mg;
485
486 $res .= $wdescr . "\n";
487
488 if (my $req = $phash->{requires}) {
489 my $tmp .= ref($req) ? join(', ', @$req) : $req;
490 $res .= "+\nNOTE: Requires option(s): `$tmp`\n";
491 }
492 $res .= "\n";
493
494 } elsif ($format eq 'short' || $format eq 'long' || $format eq 'full') {
495
496 my $defaulttxt = '';
497 if (defined(my $dv = $phash->{default})) {
498 $defaulttxt = " (default=$dv)";
499 }
500
501 my $display_name;
502 if ($style eq 'config') {
503 $display_name = "$name:";
504 } elsif ($style eq 'arg') {
505 $display_name = "-$name";
506 } elsif ($style eq 'fixed') {
507 $display_name = "<$name>";
508 } else {
509 die "unknown style '$style'";
510 }
511
512 my $tmp = sprintf " %-10s %s$defaulttxt\n", $display_name, "$type_text";
513 my $indend = " ";
514
515 $res .= Text::Wrap::wrap('', $indend, ($tmp));
516 $res .= "\n",
517 $res .= Text::Wrap::wrap($indend, $indend, ($descr)) . "\n\n";
518
519 if (my $req = $phash->{requires}) {
520 my $tmp = "Requires option(s): ";
521 $tmp .= ref($req) ? join(', ', @$req) : $req;
522 $res .= Text::Wrap::wrap($indend, $indend, ($tmp)). "\n\n";
523 }
524
525 } else {
526 die "unknown format '$format'";
527 }
528
529 return $res;
530 };
531
532 # translate parameter mapping definition
533 # $mapping_array is a array which can contain:
534 # strings ... in that case we assume it is a parameter name, and
535 # we want to load that parameter from a file
536 # [ param_name, func, desc] ... allows you to specify a arbitrary
537 # mapping func for any param
538 #
539 # Returns: a hash indexed by parameter_name,
540 # i.e. { param_name => { func => .., desc => ... } }
541 my $compute_param_mapping_hash = sub {
542 my ($mapping_array) = @_;
543
544 my $res = {};
545
546 return $res if !defined($mapping_array);
547
548 foreach my $item (@$mapping_array) {
549 my ($name, $func, $desc, $interactive);
550 if (ref($item) eq 'ARRAY') {
551 ($name, $func, $desc, $interactive) = @$item;
552 } elsif (ref($item) eq 'HASH') {
553 # just use the hash
554 $res->{$item->{name}} = $item;
555 next;
556 } else {
557 $name = $item;
558 $func = sub { return PVE::APIClient::Tools::file_get_contents($_[0]) };
559 }
560 $desc //= '<filepath>';
561 $res->{$name} = { desc => $desc, func => $func, interactive => $interactive };
562 }
563
564 return $res;
565 };
566
567 # generate usage information for command line tools
568 #
569 # $info ... method info
570 # $prefix ... usually something like "$exename $cmd" ('pvesm add')
571 # $arg_param ... list of parameters we want to get as ordered arguments
572 # on the command line (or single parameter name for lists)
573 # $fixed_param ... do not generate and info about those parameters
574 # $format:
575 # 'long' ... default (text, list all options)
576 # 'short' ... command line only (text, one line)
577 # 'full' ... text, include description
578 # 'asciidoc' ... generate asciidoc for man pages (like 'full')
579 # $param_cb ... mapping for string parameters to file path parameters
580 # $formatter_properties ... additional property definitions (passed to output formatter)
581 sub getopt_usage {
582 my ($info, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties) = @_;
583
584 $format = 'long' if !$format;
585
586 my $schema = $info->{parameters};
587 my $name = $info->{name};
588 my $prop = { %{$schema->{properties}} }; # copy
589 $prop = { %$prop, %$formatter_properties } if $formatter_properties;
590
591 my $out = '';
592
593 my $arg_hash = {};
594
595 my $args = '';
596
597 $arg_param = [ $arg_param ] if $arg_param && !ref($arg_param);
598
599 foreach my $p (@$arg_param) {
600 next if !$prop->{$p}; # just to be sure
601 my $pd = $prop->{$p};
602
603 $arg_hash->{$p} = 1;
604 $args .= " " if $args;
605 if ($pd->{format} && $pd->{format} =~ m/-list/) {
606 $args .= "{<$p>}";
607 } else {
608 $args .= $pd->{optional} ? "[<$p>]" : "<$p>";
609 }
610 }
611
612 my $argdescr = '';
613 foreach my $k (@$arg_param) {
614 next if defined($fixed_param->{$k}); # just to be sure
615 next if !$prop->{$k}; # just to be sure
616 $argdescr .= $get_property_description->($k, 'fixed', $prop->{$k}, $format);
617 }
618
619 my $idx_param = {}; # -vlan\d+ -scsi\d+
620
621 my $opts = '';
622 foreach my $k (sort keys %$prop) {
623 next if $arg_hash->{$k};
624 next if defined($fixed_param->{$k});
625
626 my $type_text = $prop->{$k}->{type} || 'string';
627
628 my $param_map = {};
629
630 if (defined($param_cb)) {
631 my $mapping = $param_cb->($name);
632 $param_map = $compute_param_mapping_hash->($mapping);
633 next if $k eq 'password' && $param_map->{$k} && !$prop->{$k}->{optional};
634 }
635
636 my $base = $k;
637 if ($k =~ m/^([a-z]+)(\d+)$/) {
638 my ($name, $idx) = ($1, $2);
639 next if $idx_param->{$name};
640 if ($idx == 0 && defined($prop->{"${name}1"})) {
641 $idx_param->{$name} = 1;
642 $base = "${name}[n]";
643 }
644 }
645
646
647 $opts .= $get_property_description->($base, 'arg', $prop->{$k}, $format, $param_map->{$k});
648
649 if (!$prop->{$k}->{optional}) {
650 $args .= " " if $args;
651 $args .= "--$base <$type_text>"
652 }
653 }
654
655 if ($format eq 'asciidoc') {
656 $out .= "*${prefix}*";
657 $out .= " `$args`" if $args;
658 $out .= $opts ? " `[OPTIONS]`\n" : "\n";
659 } else {
660 $out .= "USAGE: " if $format ne 'short';
661 $out .= "$prefix $args";
662 $out .= $opts ? " [OPTIONS]\n" : "\n";
663 }
664
665 return $out if $format eq 'short';
666
667 if ($info->{description}) {
668 if ($format eq 'asciidoc') {
669 my $desc = Text::Wrap::wrap('', '', ($info->{description}));
670 $out .= "\n$desc\n\n";
671 } elsif ($format eq 'full') {
672 my $desc = Text::Wrap::wrap(' ', ' ', ($info->{description}));
673 $out .= "\n$desc\n\n";
674 }
675 }
676
677 $out .= $argdescr if $argdescr;
678
679 $out .= $opts if $opts;
680
681 return $out;
682 }
683
684 sub usage_str {
685 my ($self, $name, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties) = @_;
686
687 my $info = $self->map_method_by_name($name);
688
689 return getopt_usage($info, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties);
690 }
691
692 # generate docs from JSON schema properties
693 sub dump_properties {
694 my ($prop, $format, $style, $filterFn) = @_;
695
696 my $raw = '';
697
698 $style //= 'config';
699
700 my $idx_param = {}; # -vlan\d+ -scsi\d+
701
702 foreach my $k (sort keys %$prop) {
703 my $phash = $prop->{$k};
704
705 next if defined($filterFn) && &$filterFn($k, $phash);
706 next if $phash->{alias};
707
708 my $base = $k;
709 if ($k =~ m/^([a-z]+)(\d+)$/) {
710 my ($name, $idx) = ($1, $2);
711 next if $idx_param->{$name};
712 if ($idx == 0 && defined($prop->{"${name}1"})) {
713 $idx_param->{$name} = 1;
714 $base = "${name}[n]";
715 }
716 }
717
718 $raw .= $get_property_description->($base, $style, $phash, $format);
719
720 next if $style ne 'config';
721
722 my $prop_fmt = $phash->{format};
723 next if !$prop_fmt;
724
725 if (ref($prop_fmt) ne 'HASH') {
726 $prop_fmt = PVE::APIClient::JSONSchema::get_format($prop_fmt);
727 }
728
729 next if !(ref($prop_fmt) && (ref($prop_fmt) eq 'HASH'));
730
731 $raw .= dump_properties($prop_fmt, $format, 'config-sub')
732
733 }
734
735 return $raw;
736 }
737
738 my $replace_file_names_with_contents = sub {
739 my ($param, $param_map) = @_;
740
741 while (my ($k, $d) = each %$param_map) {
742 next if $d->{interactive}; # handled by the JSONSchema's get_options code
743 $param->{$k} = $d->{func}->($param->{$k})
744 if defined($param->{$k});
745 }
746
747 return $param;
748 };
749
750 our $standard_output_options = {
751 'output-format' => PVE::APIClient::JSONSchema::get_standard_option('pve-output-format'),
752 noheader => {
753 description => "Do not show column headers (for 'text' format).",
754 type => 'boolean',
755 optional => 1,
756 default => 1,
757 },
758 noborder => {
759 description => "Do not draw borders (for 'text' format).",
760 type => 'boolean',
761 optional => 1,
762 default => 1,
763 },
764 quiet => {
765 description => "Suppress printing results.",
766 type => 'boolean',
767 optional => 1,
768 },
769 'human-readable' => {
770 description => "Call output rendering functions to produce human readable text.",
771 type => 'boolean',
772 optional => 1,
773 default => 1,
774 }
775 };
776
777 sub add_standard_output_properties {
778 my ($propdef, $list) = @_;
779
780 $propdef //= {};
781
782 $list //= [ keys %$standard_output_options ];
783
784 my $res = { %$propdef }; # copy
785
786 foreach my $opt (@$list) {
787 die "no such standard output option '$opt'\n" if !defined($standard_output_options->{$opt});
788 die "detected overwriten standard CLI parameter '$opt'\n" if defined($res->{$opt});
789 $res->{$opt} = $standard_output_options->{$opt};
790 }
791
792 return $res;
793 }
794
795 sub extract_standard_output_properties {
796 my ($data) = @_;
797
798 my $options = {};
799 foreach my $opt (keys %$standard_output_options) {
800 $options->{$opt} = delete $data->{$opt} if defined($data->{$opt});
801 }
802
803 return $options;
804 }
805
806 sub cli_handler {
807 my ($self, $prefix, $name, $args, $arg_param, $fixed_param, $param_cb, $formatter_properties) = @_;
808
809 my $info = $self->map_method_by_name($name);
810 my $res;
811 my $fmt_param = {};
812
813 eval {
814 my $param_map = {};
815 $param_map = $compute_param_mapping_hash->($param_cb->($name)) if $param_cb;
816 my $schema = { %{$info->{parameters}} }; # copy
817 $schema->{properties} = { %{$schema->{properties}}, %$formatter_properties } if $formatter_properties;
818 my $param = PVE::APIClient::JSONSchema::get_options($schema, $args, $arg_param, $fixed_param, $param_map);
819
820 if ($formatter_properties) {
821 foreach my $opt (keys %$formatter_properties) {
822 $fmt_param->{$opt} = delete $param->{$opt} if defined($param->{$opt});
823 }
824 }
825
826 if (defined($param_map)) {
827 $replace_file_names_with_contents->($param, $param_map);
828 }
829
830 $res = $self->handle($info, $param);
831 };
832 if (my $err = $@) {
833 my $ec = ref($err);
834
835 die $err if !$ec || $ec ne "PVE::APIClient::Exception" || !$err->is_param_exc();
836
837 $err->{usage} = $self->usage_str($name, $prefix, $arg_param, $fixed_param, 'short', $param_cb, $formatter_properties);
838
839 die $err;
840 }
841
842 return wantarray ? ($res, $fmt_param) : $res;
843 }
844
845 # utility methods
846 # note: this modifies the original hash by adding the id property
847 sub hash_to_array {
848 my ($hash, $idprop) = @_;
849
850 my $res = [];
851 return $res if !$hash;
852
853 foreach my $k (keys %$hash) {
854 $hash->{$k}->{$idprop} = $k;
855 push @$res, $hash->{$k};
856 }
857
858 return $res;
859 }
860
861 1;