]> git.proxmox.com Git - pve-common.git/blame - src/PVE/RESTHandler.pm
small code/comment cleanups
[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
520 $res .= $wdescr . "\n";
8fa050cd
DM
521
522 if (my $req = $phash->{requires}) {
523 my $tmp .= ref($req) ? join(', ', @$req) : $req;
524 $res .= "+\nNOTE: Requires option(s): `$tmp`\n";
525 }
526 $res .= "\n";
527
b0e5e9fa 528 } elsif ($format eq 'short' || $format eq 'long' || $format eq 'full') {
8fa050cd
DM
529
530 my $defaulttxt = '';
531 if (defined(my $dv = $phash->{default})) {
532 $defaulttxt = " (default=$dv)";
533 }
534
df79b428
DM
535 my $display_name;
536 if ($style eq 'config') {
537 $display_name = "$name:";
538 } elsif ($style eq 'arg') {
539 $display_name = "-$name";
540 } elsif ($style eq 'fixed') {
541 $display_name = "<$name>";
542 } else {
543 die "unknown style '$style'";
544 }
8fa050cd 545
cc6792c7 546 my $tmp = sprintf " %-10s %s%s\n", $display_name, "$type_text", "$defaulttxt";
8fa050cd
DM
547 my $indend = " ";
548
549 $res .= Text::Wrap::wrap('', $indend, ($tmp));
550 $res .= "\n",
551 $res .= Text::Wrap::wrap($indend, $indend, ($descr)) . "\n\n";
552
553 if (my $req = $phash->{requires}) {
554 my $tmp = "Requires option(s): ";
555 $tmp .= ref($req) ? join(', ', @$req) : $req;
556 $res .= Text::Wrap::wrap($indend, $indend, ($tmp)). "\n\n";
557 }
558
559 } else {
560 die "unknown format '$format'";
561 }
562
563 return $res;
564};
565
dfc6cff8
DM
566# translate parameter mapping definition
567# $mapping_array is a array which can contain:
568# strings ... in that case we assume it is a parameter name, and
569# we want to load that parameter from a file
570# [ param_name, func, desc] ... allows you to specify a arbitrary
571# mapping func for any param
572#
573# Returns: a hash indexed by parameter_name,
574# i.e. { param_name => { func => .., desc => ... } }
575my $compute_param_mapping_hash = sub {
576 my ($mapping_array) = @_;
577
578 my $res = {};
579
580 return $res if !defined($mapping_array);
581
582 foreach my $item (@$mapping_array) {
c7171ff2 583 my ($name, $func, $desc, $interactive);
dfc6cff8 584 if (ref($item) eq 'ARRAY') {
c7171ff2 585 ($name, $func, $desc, $interactive) = @$item;
a1c7edda
DC
586 } elsif (ref($item) eq 'HASH') {
587 # just use the hash
588 $res->{$item->{name}} = $item;
589 next;
dfc6cff8
DM
590 } else {
591 $name = $item;
592 $func = sub { return PVE::Tools::file_get_contents($_[0]) };
593 }
594 $desc //= '<filepath>';
c7171ff2 595 $res->{$name} = { desc => $desc, func => $func, interactive => $interactive };
dfc6cff8
DM
596 }
597
598 return $res;
599};
600
e143e9d8
DM
601# generate usage information for command line tools
602#
c03b7509 603# $info ... method info
e143e9d8 604# $prefix ... usually something like "$exename $cmd" ('pvesm add')
9bbc4e17 605# $arg_param ... list of parameters we want to get as ordered arguments
1d21344c 606# on the command line (or single parameter name for lists)
e143e9d8
DM
607# $fixed_param ... do not generate and info about those parameters
608# $format:
b0e5e9fa
DM
609# 'long' ... default (text, list all options)
610# 'short' ... command line only (text, one line)
611# 'full' ... text, include description
fe3f1fde 612# 'asciidoc' ... generate asciidoc for man pages (like 'full')
9da27228
DM
613# $param_cb ... mapping for string parameters to file path parameters
614# $formatter_properties ... additional property definitions (passed to output formatter)
c03b7509 615sub getopt_usage {
9da27228 616 my ($info, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties) = @_;
e143e9d8
DM
617
618 $format = 'long' if !$format;
619
e143e9d8 620 my $schema = $info->{parameters};
c03b7509 621 my $name = $info->{name};
772038d4
TL
622 my $prop = {};
623 if ($schema->{properties}) {
624 $prop = { %{$schema->{properties}} }; # copy
625 }
62c66c47
DM
626
627 my $has_output_format_option = $formatter_properties->{'output-format'} ? 1 : 0;
628
629 if ($formatter_properties) {
630 foreach my $key (keys %$formatter_properties) {
631 if (!$standard_output_options->{$key}) {
632 $prop->{$key} = $formatter_properties->{$key};
633 }
5c59d8f9
DM
634 }
635 }
636
637 # also remove $standard_output_options from $prop (pvesh, pveclient)
638 if ($prop->{'output-format'}) {
639 $has_output_format_option = 1;
640 foreach my $key (keys %$prop) {
641 if ($standard_output_options->{$key}) {
642 delete $prop->{$key};
643 }
62c66c47
DM
644 }
645 }
e143e9d8
DM
646
647 my $out = '';
648
649 my $arg_hash = {};
650
651 my $args = '';
1d21344c
DM
652
653 $arg_param = [ $arg_param ] if $arg_param && !ref($arg_param);
654
e143e9d8
DM
655 foreach my $p (@$arg_param) {
656 next if !$prop->{$p}; # just to be sure
1d21344c 657 my $pd = $prop->{$p};
e143e9d8
DM
658
659 $arg_hash->{$p} = 1;
660 $args .= " " if $args;
1d21344c 661 if ($pd->{format} && $pd->{format} =~ m/-list/) {
7f0f0610 662 $args .= "{<$p>}";
1d21344c
DM
663 } else {
664 $args .= $pd->{optional} ? "[<$p>]" : "<$p>";
665 }
e143e9d8
DM
666 }
667
e143e9d8
DM
668 my $argdescr = '';
669 foreach my $k (@$arg_param) {
670 next if defined($fixed_param->{$k}); # just to be sure
671 next if !$prop->{$k}; # just to be sure
4842b651 672 $argdescr .= $get_property_description->($k, 'fixed', $prop->{$k}, $format);
e143e9d8
DM
673 }
674
675 my $idx_param = {}; # -vlan\d+ -scsi\d+
676
677 my $opts = '';
678 foreach my $k (sort keys %$prop) {
679 next if $arg_hash->{$k};
680 next if defined($fixed_param->{$k});
681
77096a6f 682 my $type_text = $prop->{$k}->{type} || 'string';
e143e9d8 683
968bcf45 684 my $param_map = {};
4842b651 685
968bcf45
TL
686 if (defined($param_cb)) {
687 my $mapping = $param_cb->($name);
688 $param_map = $compute_param_mapping_hash->($mapping);
689 next if $k eq 'password' && $param_map->{$k} && !$prop->{$k}->{optional};
4842b651 690 }
e143e9d8
DM
691
692 my $base = $k;
693 if ($k =~ m/^([a-z]+)(\d+)$/) {
b546f33e 694 my ($name, $idx) = ($1, $2);
e143e9d8 695 next if $idx_param->{$name};
b54ad320 696 if ($idx == 0 && defined($prop->{"${name}1"})) {
f922b8a8
FG
697 $idx_param->{$name} = 1;
698 $base = "${name}[n]";
699 }
e143e9d8
DM
700 }
701
dfc6cff8 702
968bcf45 703 $opts .= $get_property_description->($base, 'arg', $prop->{$k}, $format, $param_map->{$k});
e143e9d8
DM
704
705 if (!$prop->{$k}->{optional}) {
706 $args .= " " if $args;
a4f181a3 707 $args .= "--$base <$type_text>"
e143e9d8 708 }
9bbc4e17 709 }
e143e9d8 710
fe3f1fde
DM
711 if ($format eq 'asciidoc') {
712 $out .= "*${prefix}*";
713 $out .= " `$args`" if $args;
62c66c47
DM
714 $out .= " `[OPTIONS]`" if $opts;
715 $out .= " `[FORMAT_OPTIONS]`" if $has_output_format_option;
716 $out .= "\n";
fe3f1fde
DM
717 } else {
718 $out .= "USAGE: " if $format ne 'short';
719 $out .= "$prefix $args";
62c66c47
DM
720 $out .= " [OPTIONS]" if $opts;
721 $out .= " [FORMAT_OPTIONS]" if $has_output_format_option;
722 $out .= "\n";
fe3f1fde 723 }
e143e9d8
DM
724
725 return $out if $format eq 'short';
726
fe3f1fde
DM
727 if ($info->{description}) {
728 if ($format eq 'asciidoc') {
729 my $desc = Text::Wrap::wrap('', '', ($info->{description}));
730 $out .= "\n$desc\n\n";
731 } elsif ($format eq 'full') {
732 my $desc = Text::Wrap::wrap(' ', ' ', ($info->{description}));
733 $out .= "\n$desc\n\n";
734 }
e143e9d8
DM
735 }
736
737 $out .= $argdescr if $argdescr;
738
739 $out .= $opts if $opts;
740
741 return $out;
742}
743
c03b7509 744sub usage_str {
9da27228 745 my ($self, $name, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties) = @_;
c03b7509
DM
746
747 my $info = $self->map_method_by_name($name);
748
9da27228 749 return getopt_usage($info, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties);
c03b7509
DM
750}
751
8fa050cd
DM
752# generate docs from JSON schema properties
753sub dump_properties {
df79b428 754 my ($prop, $format, $style, $filterFn) = @_;
8fa050cd
DM
755
756 my $raw = '';
757
df79b428 758 $style //= 'config';
9bbc4e17 759
8fa050cd
DM
760 my $idx_param = {}; # -vlan\d+ -scsi\d+
761
762 foreach my $k (sort keys %$prop) {
763 my $phash = $prop->{$k};
764
765 next if defined($filterFn) && &$filterFn($k, $phash);
32f8e0c7 766 next if $phash->{alias};
8fa050cd
DM
767
768 my $base = $k;
769 if ($k =~ m/^([a-z]+)(\d+)$/) {
b546f33e 770 my ($name, $idx) = ($1, $2);
8fa050cd 771 next if $idx_param->{$name};
b54ad320 772 if ($idx == 0 && defined($prop->{"${name}1"})) {
f922b8a8
FG
773 $idx_param->{$name} = 1;
774 $base = "${name}[n]";
775 }
8fa050cd
DM
776 }
777
4842b651 778 $raw .= $get_property_description->($base, $style, $phash, $format);
32f8e0c7
DM
779
780 next if $style ne 'config';
781
782 my $prop_fmt = $phash->{format};
783 next if !$prop_fmt;
784
785 if (ref($prop_fmt) ne 'HASH') {
786 $prop_fmt = PVE::JSONSchema::get_format($prop_fmt);
787 }
788
789 next if !(ref($prop_fmt) && (ref($prop_fmt) eq 'HASH'));
790
791 $raw .= dump_properties($prop_fmt, $format, 'config-sub')
9bbc4e17 792
8fa050cd 793 }
b0e5e9fa 794
8fa050cd
DM
795 return $raw;
796}
797
408976c6 798my $replace_file_names_with_contents = sub {
968bcf45 799 my ($param, $param_map) = @_;
408976c6 800
968bcf45 801 while (my ($k, $d) = each %$param_map) {
c7171ff2 802 next if $d->{interactive}; # handled by the JSONSchema's get_options code
dfc6cff8
DM
803 $param->{$k} = $d->{func}->($param->{$k})
804 if defined($param->{$k});
408976c6
FG
805 }
806
807 return $param;
808};
809
4cbcd138
DM
810sub add_standard_output_properties {
811 my ($propdef, $list) = @_;
0adee985 812
4cbcd138 813 $propdef //= {};
0adee985 814
4cbcd138
DM
815 $list //= [ keys %$standard_output_options ];
816
817 my $res = { %$propdef }; # copy
818
819 foreach my $opt (@$list) {
820 die "no such standard output option '$opt'\n" if !defined($standard_output_options->{$opt});
821 die "detected overwriten standard CLI parameter '$opt'\n" if defined($res->{$opt});
822 $res->{$opt} = $standard_output_options->{$opt};
823 }
824
825 return $res;
826}
827
828sub extract_standard_output_properties {
829 my ($data) = @_;
830
831 my $options = {};
832 foreach my $opt (keys %$standard_output_options) {
833 $options->{$opt} = delete $data->{$opt} if defined($data->{$opt});
834 }
835
836 return $options;
837}
0adee985 838
e143e9d8 839sub cli_handler {
9da27228 840 my ($self, $prefix, $name, $args, $arg_param, $fixed_param, $param_cb, $formatter_properties) = @_;
e143e9d8
DM
841
842 my $info = $self->map_method_by_name($name);
e143e9d8 843 my $res;
9da27228
DM
844 my $fmt_param = {};
845
e143e9d8 846 eval {
968bcf45
TL
847 my $param_map = {};
848 $param_map = $compute_param_mapping_hash->($param_cb->($name)) if $param_cb;
9da27228
DM
849 my $schema = { %{$info->{parameters}} }; # copy
850 $schema->{properties} = { %{$schema->{properties}}, %$formatter_properties } if $formatter_properties;
851 my $param = PVE::JSONSchema::get_options($schema, $args, $arg_param, $fixed_param, $param_map);
852
853 if ($formatter_properties) {
854 foreach my $opt (keys %$formatter_properties) {
855 $fmt_param->{$opt} = delete $param->{$opt} if defined($param->{$opt});
856 }
857 }
dfc6cff8 858
968bcf45
TL
859 if (defined($param_map)) {
860 $replace_file_names_with_contents->($param, $param_map);
dfc6cff8
DM
861 }
862
1b44e6fe 863 $res = $self->handle($info, $param, 1);
e143e9d8
DM
864 };
865 if (my $err = $@) {
866 my $ec = ref($err);
867
868 die $err if !$ec || $ec ne "PVE::Exception" || !$err->is_param_exc();
9bbc4e17 869
9da27228 870 $err->{usage} = $self->usage_str($name, $prefix, $arg_param, $fixed_param, 'short', $param_cb, $formatter_properties);
e143e9d8
DM
871
872 die $err;
873 }
874
9da27228 875 return wantarray ? ($res, $fmt_param) : $res;
e143e9d8
DM
876}
877
878# utility methods
879# note: this modifies the original hash by adding the id property
880sub hash_to_array {
881 my ($hash, $idprop) = @_;
882
883 my $res = [];
884 return $res if !$hash;
885
886 foreach my $k (keys %$hash) {
887 $hash->{$k}->{$idprop} = $k;
888 push @$res, $hash->{$k};
889 }
890
891 return $res;
892}
893
8941;