]>
Commit | Line | Data |
---|---|---|
1 | package PVE::RESTHandler; | |
2 | ||
3 | use strict; | |
4 | no strict 'refs'; # our autoload requires this | |
5 | use warnings; | |
6 | use PVE::SafeSyslog; | |
7 | use PVE::Exception qw(raise raise_param_exc); | |
8 | use PVE::JSONSchema; | |
9 | use PVE::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 | our $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 | ||
47 | sub 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 more complex types, to | |
73 | # 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'; | |
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 | *{$sub} = sub { | |
334 | my $self = shift; | |
335 | return $self->handle($info, @_); | |
336 | }; | |
337 | goto &$AUTOLOAD; | |
338 | } | |
339 | ||
340 | sub method_attributes { | |
341 | my ($self) = @_; | |
342 | ||
343 | return $method_registry->{$self}; | |
344 | } | |
345 | ||
346 | sub map_method_by_name { | |
347 | my ($self, $name) = @_; | |
348 | ||
349 | my $info = $method_by_name->{$self}->{$name}; | |
350 | die "no such method '${self}::$name'\n" if !$info; | |
351 | ||
352 | return $info; | |
353 | } | |
354 | ||
355 | sub map_path_to_methods { | |
356 | my ($class, $stack, $uri_param, $pathmatchref) = @_; | |
357 | ||
358 | my $path_lookup = $method_path_lookup->{$class}; | |
359 | ||
360 | # Note: $pathmatchref can be used to obtain path including | |
361 | # uri patterns like '/cluster/firewall/groups/{group}'. | |
362 | # Used by pvesh to display help | |
363 | if (defined($pathmatchref)) { | |
364 | $$pathmatchref = '' if !$$pathmatchref; | |
365 | } | |
366 | ||
367 | while (defined(my $comp = shift @$stack)) { | |
368 | return undef if !$path_lookup; # not registerd? | |
369 | if ($path_lookup->{regex}) { | |
370 | my $name = $path_lookup->{regex}->{match_name}; | |
371 | my $regex = $path_lookup->{regex}->{match_re}; | |
372 | ||
373 | return undef if $comp !~ m/^($regex)$/; | |
374 | $uri_param->{$name} = $1; | |
375 | $path_lookup = $path_lookup->{regex}; | |
376 | $$pathmatchref .= '/{' . $name . '}' if defined($pathmatchref); | |
377 | } elsif ($path_lookup->{folders}) { | |
378 | $path_lookup = $path_lookup->{folders}->{$comp}; | |
379 | $$pathmatchref .= '/' . $comp if defined($pathmatchref); | |
380 | } else { | |
381 | die "internal error"; | |
382 | } | |
383 | ||
384 | return undef if !$path_lookup; | |
385 | ||
386 | if (my $info = $path_lookup->{SUBCLASS}) { | |
387 | $class = $info->{subclass}; | |
388 | ||
389 | my $fd = $info->{fragmentDelimiter}; | |
390 | ||
391 | if (defined($fd)) { | |
392 | # we only support the empty string '' (match whole URI) | |
393 | die "unsupported fragmentDelimiter '$fd'" | |
394 | if $fd ne ''; | |
395 | ||
396 | $stack = [ join ('/', @$stack) ] if scalar(@$stack) > 1; | |
397 | } | |
398 | $path_lookup = $method_path_lookup->{$class}; | |
399 | } | |
400 | } | |
401 | ||
402 | return undef if !$path_lookup; | |
403 | ||
404 | return ($class, $path_lookup); | |
405 | } | |
406 | ||
407 | sub find_handler { | |
408 | my ($class, $method, $path, $uri_param, $pathmatchref) = @_; | |
409 | ||
410 | my $stack = [ grep { length($_) > 0 } split('\/+' , $path)]; # skip empty fragments | |
411 | ||
412 | my ($handler_class, $path_info); | |
413 | eval { | |
414 | ($handler_class, $path_info) = $class->map_path_to_methods($stack, $uri_param, $pathmatchref); | |
415 | }; | |
416 | my $err = $@; | |
417 | syslog('err', $err) if $err; | |
418 | ||
419 | return undef if !($handler_class && $path_info); | |
420 | ||
421 | my $method_info = $path_info->{$method}; | |
422 | ||
423 | return undef if !$method_info; | |
424 | ||
425 | return ($handler_class, $method_info); | |
426 | } | |
427 | ||
428 | sub handle { | |
429 | my ($self, $info, $param, $result_verification) = @_; | |
430 | ||
431 | my $func = $info->{code}; | |
432 | ||
433 | if (!($info->{name} && $func)) { | |
434 | raise("Method lookup failed ('$info->{name}')\n", code => HTTP_INTERNAL_SERVER_ERROR); | |
435 | } | |
436 | ||
437 | if (my $schema = $info->{parameters}) { | |
438 | # warn "validate ". Dumper($param}) . "\n" . Dumper($schema); | |
439 | PVE::JSONSchema::validate($param, $schema); | |
440 | # untaint data (already validated) | |
441 | my $extra = delete $param->{'extra-args'}; | |
442 | while (my ($key, $val) = each %$param) { | |
443 | if (defined($val)) { | |
444 | ($param->{$key}) = $val =~ /^(.*)$/s; | |
445 | } else { | |
446 | $param->{$key} = undef; | |
447 | } | |
448 | } | |
449 | $param->{'extra-args'} = [map { /^(.*)$/ } @$extra] if $extra; | |
450 | } | |
451 | ||
452 | my $result = $func->($param); # the actual API code execution call | |
453 | ||
454 | if ($result_verification && (my $schema = $info->{returns})) { | |
455 | # return validation is rather lose-lose, as it can require quite a bit of time and lead to | |
456 | # false-positive errors, any HTTP API handler should avoid enabling it by default. | |
457 | PVE::JSONSchema::validate($result, $schema, "Result verification failed\n"); | |
458 | } | |
459 | return $result; | |
460 | } | |
461 | ||
462 | # format option, display type and description | |
463 | # $name: option name | |
464 | # $display_name: for example "-$name" of "<$name>", pass undef to use "$name:" | |
465 | # $phash: json schema property hash | |
466 | # $format: 'asciidoc', 'short', 'long' or 'full' | |
467 | # $style: 'config', 'config-sub', 'arg' or 'fixed' | |
468 | # $mapdef: parameter mapping ({ desc => XXX, func => sub {...} }) | |
469 | my $get_property_description = sub { | |
470 | my ($name, $style, $phash, $format, $mapdef) = @_; | |
471 | ||
472 | my $res = ''; | |
473 | ||
474 | $format = 'asciidoc' if !defined($format); | |
475 | ||
476 | my $descr = $phash->{description} || "no description available"; | |
477 | ||
478 | if ($phash->{verbose_description} && | |
479 | ($style eq 'config' || $style eq 'config-sub')) { | |
480 | $descr = $phash->{verbose_description}; | |
481 | } | |
482 | ||
483 | chomp $descr; | |
484 | ||
485 | my $type_text = PVE::JSONSchema::schema_get_type_text($phash, $style); | |
486 | ||
487 | if ($mapdef && $phash->{type} eq 'string') { | |
488 | $type_text = $mapdef->{desc}; | |
489 | } | |
490 | ||
491 | if ($format eq 'asciidoc') { | |
492 | ||
493 | if ($style eq 'config') { | |
494 | $res .= "`$name`: "; | |
495 | } elsif ($style eq 'config-sub') { | |
496 | $res .= "`$name`="; | |
497 | } elsif ($style eq 'arg') { | |
498 | $res .= "`--$name` "; | |
499 | } elsif ($style eq 'fixed') { | |
500 | $res .= "`<$name>`: "; | |
501 | } else { | |
502 | die "unknown style '$style'"; | |
503 | } | |
504 | ||
505 | $res .= "`$type_text` " if $type_text; | |
506 | ||
507 | if (defined(my $dv = $phash->{default})) { | |
508 | $res .= "('default =' `$dv`)"; | |
509 | } | |
510 | ||
511 | if ($style eq 'config-sub') { | |
512 | $res .= ";;\n\n"; | |
513 | } else { | |
514 | $res .= "::\n\n"; | |
515 | } | |
516 | ||
517 | my $wdescr = $descr; | |
518 | chomp $wdescr; | |
519 | $wdescr =~ s/^$/+/mg; | |
520 | ||
521 | $res .= $wdescr . "\n"; | |
522 | ||
523 | if (my $req = $phash->{requires}) { | |
524 | my $tmp .= ref($req) ? join(', ', @$req) : $req; | |
525 | $res .= "+\nNOTE: Requires option(s): `$tmp`\n"; | |
526 | } | |
527 | $res .= "\n"; | |
528 | ||
529 | } elsif ($format eq 'short' || $format eq 'long' || $format eq 'full') { | |
530 | ||
531 | my $defaulttxt = ''; | |
532 | if (defined(my $dv = $phash->{default})) { | |
533 | $defaulttxt = " (default=$dv)"; | |
534 | } | |
535 | ||
536 | my $display_name; | |
537 | if ($style eq 'config') { | |
538 | $display_name = "$name:"; | |
539 | } elsif ($style eq 'arg') { | |
540 | $display_name = "-$name"; | |
541 | } elsif ($style eq 'fixed') { | |
542 | $display_name = "<$name>"; | |
543 | } else { | |
544 | die "unknown style '$style'"; | |
545 | } | |
546 | ||
547 | my $tmp = sprintf " %-10s %s%s\n", $display_name, "$type_text", "$defaulttxt"; | |
548 | my $indend = " "; | |
549 | ||
550 | $res .= Text::Wrap::wrap('', $indend, ($tmp)); | |
551 | $res .= "\n", | |
552 | $res .= Text::Wrap::wrap($indend, $indend, ($descr)) . "\n\n"; | |
553 | ||
554 | if (my $req = $phash->{requires}) { | |
555 | my $tmp = "Requires option(s): "; | |
556 | $tmp .= ref($req) ? join(', ', @$req) : $req; | |
557 | $res .= Text::Wrap::wrap($indend, $indend, ($tmp)). "\n\n"; | |
558 | } | |
559 | ||
560 | } else { | |
561 | die "unknown format '$format'"; | |
562 | } | |
563 | ||
564 | return $res; | |
565 | }; | |
566 | ||
567 | # translate parameter mapping definition | |
568 | # $mapping_array is a array which can contain: | |
569 | # strings ... in that case we assume it is a parameter name, and | |
570 | # we want to load that parameter from a file | |
571 | # [ param_name, func, desc] ... allows you to specify a arbitrary | |
572 | # mapping func for any param | |
573 | # | |
574 | # Returns: a hash indexed by parameter_name, | |
575 | # i.e. { param_name => { func => .., desc => ... } } | |
576 | my $compute_param_mapping_hash = sub { | |
577 | my ($mapping_array) = @_; | |
578 | ||
579 | my $res = {}; | |
580 | ||
581 | return $res if !defined($mapping_array); | |
582 | ||
583 | foreach my $item (@$mapping_array) { | |
584 | my ($name, $func, $desc, $interactive); | |
585 | if (ref($item) eq 'ARRAY') { | |
586 | ($name, $func, $desc, $interactive) = @$item; | |
587 | } elsif (ref($item) eq 'HASH') { | |
588 | # just use the hash | |
589 | $res->{$item->{name}} = $item; | |
590 | next; | |
591 | } else { | |
592 | $name = $item; | |
593 | $func = sub { return PVE::Tools::file_get_contents($_[0]) }; | |
594 | } | |
595 | $desc //= '<filepath>'; | |
596 | $res->{$name} = { desc => $desc, func => $func, interactive => $interactive }; | |
597 | } | |
598 | ||
599 | return $res; | |
600 | }; | |
601 | ||
602 | # generate usage information for command line tools | |
603 | # | |
604 | # $info ... method info | |
605 | # $prefix ... usually something like "$exename $cmd" ('pvesm add') | |
606 | # $arg_param ... list of parameters we want to get as ordered arguments | |
607 | # on the command line (or single parameter name for lists) | |
608 | # $fixed_param ... do not generate and info about those parameters | |
609 | # $format: | |
610 | # 'long' ... default (text, list all options) | |
611 | # 'short' ... command line only (text, one line) | |
612 | # 'full' ... text, include description | |
613 | # 'asciidoc' ... generate asciidoc for man pages (like 'full') | |
614 | # $param_cb ... mapping for string parameters to file path parameters | |
615 | # $formatter_properties ... additional property definitions (passed to output formatter) | |
616 | sub getopt_usage { | |
617 | my ($info, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties) = @_; | |
618 | ||
619 | $format = 'long' if !$format; | |
620 | ||
621 | my $schema = $info->{parameters}; | |
622 | my $name = $info->{name}; | |
623 | my $prop = {}; | |
624 | if ($schema->{properties}) { | |
625 | $prop = { %{$schema->{properties}} }; # copy | |
626 | } | |
627 | ||
628 | my $has_output_format_option = $formatter_properties->{'output-format'} ? 1 : 0; | |
629 | ||
630 | if ($formatter_properties) { | |
631 | foreach my $key (keys %$formatter_properties) { | |
632 | if (!$standard_output_options->{$key}) { | |
633 | $prop->{$key} = $formatter_properties->{$key}; | |
634 | } | |
635 | } | |
636 | } | |
637 | ||
638 | # also remove $standard_output_options from $prop (pvesh, pveclient) | |
639 | if ($prop->{'output-format'}) { | |
640 | $has_output_format_option = 1; | |
641 | foreach my $key (keys %$prop) { | |
642 | if ($standard_output_options->{$key}) { | |
643 | delete $prop->{$key}; | |
644 | } | |
645 | } | |
646 | } | |
647 | ||
648 | my $out = ''; | |
649 | ||
650 | my $arg_hash = {}; | |
651 | ||
652 | my $args = ''; | |
653 | ||
654 | $arg_param = [ $arg_param ] if $arg_param && !ref($arg_param); | |
655 | ||
656 | foreach my $p (@$arg_param) { | |
657 | next if !$prop->{$p}; # just to be sure | |
658 | my $pd = $prop->{$p}; | |
659 | ||
660 | $arg_hash->{$p} = 1; | |
661 | $args .= " " if $args; | |
662 | if ($pd->{format} && $pd->{format} =~ m/-list/) { | |
663 | $args .= "{<$p>}"; | |
664 | } else { | |
665 | $args .= $pd->{optional} ? "[<$p>]" : "<$p>"; | |
666 | } | |
667 | } | |
668 | ||
669 | my $argdescr = ''; | |
670 | foreach my $k (@$arg_param) { | |
671 | next if defined($fixed_param->{$k}); # just to be sure | |
672 | next if !$prop->{$k}; # just to be sure | |
673 | $argdescr .= $get_property_description->($k, 'fixed', $prop->{$k}, $format); | |
674 | } | |
675 | ||
676 | my $idx_param = {}; # -vlan\d+ -scsi\d+ | |
677 | ||
678 | my $opts = ''; | |
679 | foreach my $k (sort keys %$prop) { | |
680 | next if $arg_hash->{$k}; | |
681 | next if defined($fixed_param->{$k}); | |
682 | ||
683 | my $type_text = $prop->{$k}->{type} || 'string'; | |
684 | ||
685 | my $param_map = {}; | |
686 | ||
687 | if (defined($param_cb)) { | |
688 | my $mapping = $param_cb->($name); | |
689 | $param_map = $compute_param_mapping_hash->($mapping); | |
690 | next if $k eq 'password' && $param_map->{$k} && !$prop->{$k}->{optional}; | |
691 | } | |
692 | ||
693 | my $base = $k; | |
694 | if ($k =~ m/^([a-z]+)(\d+)$/) { | |
695 | my ($name, $idx) = ($1, $2); | |
696 | next if $idx_param->{$name}; | |
697 | if ($idx == 0 && defined($prop->{"${name}1"})) { | |
698 | $idx_param->{$name} = 1; | |
699 | $base = "${name}[n]"; | |
700 | } | |
701 | } | |
702 | ||
703 | ||
704 | $opts .= $get_property_description->($base, 'arg', $prop->{$k}, $format, $param_map->{$k}); | |
705 | ||
706 | if (!$prop->{$k}->{optional}) { | |
707 | $args .= " " if $args; | |
708 | $args .= "--$base <$type_text>" | |
709 | } | |
710 | } | |
711 | ||
712 | if ($format eq 'asciidoc') { | |
713 | $out .= "*${prefix}*"; | |
714 | $out .= " `$args`" if $args; | |
715 | $out .= " `[OPTIONS]`" if $opts; | |
716 | $out .= " `[FORMAT_OPTIONS]`" if $has_output_format_option; | |
717 | $out .= "\n"; | |
718 | } else { | |
719 | $out .= "USAGE: " if $format ne 'short'; | |
720 | $out .= "$prefix $args"; | |
721 | $out .= " [OPTIONS]" if $opts; | |
722 | $out .= " [FORMAT_OPTIONS]" if $has_output_format_option; | |
723 | $out .= "\n"; | |
724 | } | |
725 | ||
726 | return $out if $format eq 'short'; | |
727 | ||
728 | if ($info->{description}) { | |
729 | if ($format eq 'asciidoc') { | |
730 | my $desc = Text::Wrap::wrap('', '', ($info->{description})); | |
731 | $out .= "\n$desc\n\n"; | |
732 | } elsif ($format eq 'full') { | |
733 | my $desc = Text::Wrap::wrap(' ', ' ', ($info->{description})); | |
734 | $out .= "\n$desc\n\n"; | |
735 | } | |
736 | } | |
737 | ||
738 | $out .= $argdescr if $argdescr; | |
739 | ||
740 | $out .= $opts if $opts; | |
741 | ||
742 | return $out; | |
743 | } | |
744 | ||
745 | sub usage_str { | |
746 | my ($self, $name, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties) = @_; | |
747 | ||
748 | my $info = $self->map_method_by_name($name); | |
749 | ||
750 | return getopt_usage($info, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties); | |
751 | } | |
752 | ||
753 | # generate docs from JSON schema properties | |
754 | sub dump_properties { | |
755 | my ($prop, $format, $style, $filterFn) = @_; | |
756 | ||
757 | my $raw = ''; | |
758 | ||
759 | $style //= 'config'; | |
760 | ||
761 | my $idx_param = {}; # -vlan\d+ -scsi\d+ | |
762 | ||
763 | foreach my $k (sort keys %$prop) { | |
764 | my $phash = $prop->{$k}; | |
765 | ||
766 | next if defined($filterFn) && &$filterFn($k, $phash); | |
767 | next if $phash->{alias}; | |
768 | ||
769 | my $base = $k; | |
770 | if ($k =~ m/^([a-z]+)(\d+)$/) { | |
771 | my ($name, $idx) = ($1, $2); | |
772 | next if $idx_param->{$name}; | |
773 | if ($idx == 0 && defined($prop->{"${name}1"})) { | |
774 | $idx_param->{$name} = 1; | |
775 | $base = "${name}[n]"; | |
776 | } | |
777 | } | |
778 | ||
779 | $raw .= $get_property_description->($base, $style, $phash, $format); | |
780 | ||
781 | next if $style ne 'config'; | |
782 | ||
783 | my $prop_fmt = $phash->{format}; | |
784 | next if !$prop_fmt; | |
785 | ||
786 | if (ref($prop_fmt) ne 'HASH') { | |
787 | $prop_fmt = PVE::JSONSchema::get_format($prop_fmt); | |
788 | } | |
789 | ||
790 | next if !(ref($prop_fmt) && (ref($prop_fmt) eq 'HASH')); | |
791 | ||
792 | $raw .= dump_properties($prop_fmt, $format, 'config-sub') | |
793 | ||
794 | } | |
795 | ||
796 | return $raw; | |
797 | } | |
798 | ||
799 | my $replace_file_names_with_contents = sub { | |
800 | my ($param, $param_map) = @_; | |
801 | ||
802 | while (my ($k, $d) = each %$param_map) { | |
803 | next if $d->{interactive}; # handled by the JSONSchema's get_options code | |
804 | $param->{$k} = $d->{func}->($param->{$k}) | |
805 | if defined($param->{$k}); | |
806 | } | |
807 | ||
808 | return $param; | |
809 | }; | |
810 | ||
811 | sub add_standard_output_properties { | |
812 | my ($propdef, $list) = @_; | |
813 | ||
814 | $propdef //= {}; | |
815 | ||
816 | $list //= [ keys %$standard_output_options ]; | |
817 | ||
818 | my $res = { %$propdef }; # copy | |
819 | ||
820 | foreach my $opt (@$list) { | |
821 | die "no such standard output option '$opt'\n" if !defined($standard_output_options->{$opt}); | |
822 | die "detected overwriten standard CLI parameter '$opt'\n" if defined($res->{$opt}); | |
823 | $res->{$opt} = $standard_output_options->{$opt}; | |
824 | } | |
825 | ||
826 | return $res; | |
827 | } | |
828 | ||
829 | sub extract_standard_output_properties { | |
830 | my ($data) = @_; | |
831 | ||
832 | my $options = {}; | |
833 | foreach my $opt (keys %$standard_output_options) { | |
834 | $options->{$opt} = delete $data->{$opt} if defined($data->{$opt}); | |
835 | } | |
836 | ||
837 | return $options; | |
838 | } | |
839 | ||
840 | sub cli_handler { | |
841 | my ($self, $prefix, $name, $args, $arg_param, $fixed_param, $param_cb, $formatter_properties) = @_; | |
842 | ||
843 | my $info = $self->map_method_by_name($name); | |
844 | my $res; | |
845 | my $fmt_param = {}; | |
846 | ||
847 | eval { | |
848 | my $param_map = {}; | |
849 | $param_map = $compute_param_mapping_hash->($param_cb->($name)) if $param_cb; | |
850 | my $schema = { %{$info->{parameters}} }; # copy | |
851 | $schema->{properties} = { %{$schema->{properties}}, %$formatter_properties } if $formatter_properties; | |
852 | my $param = PVE::JSONSchema::get_options($schema, $args, $arg_param, $fixed_param, $param_map); | |
853 | ||
854 | if ($formatter_properties) { | |
855 | foreach my $opt (keys %$formatter_properties) { | |
856 | $fmt_param->{$opt} = delete $param->{$opt} if defined($param->{$opt}); | |
857 | } | |
858 | } | |
859 | ||
860 | if (defined($param_map)) { | |
861 | $replace_file_names_with_contents->($param, $param_map); | |
862 | } | |
863 | ||
864 | $res = $self->handle($info, $param, 1); | |
865 | }; | |
866 | if (my $err = $@) { | |
867 | my $ec = ref($err); | |
868 | ||
869 | die $err if !$ec || $ec ne "PVE::Exception" || !$err->is_param_exc(); | |
870 | ||
871 | $err->{usage} = $self->usage_str($name, $prefix, $arg_param, $fixed_param, 'short', $param_cb, $formatter_properties); | |
872 | ||
873 | die $err; | |
874 | } | |
875 | ||
876 | return wantarray ? ($res, $fmt_param) : $res; | |
877 | } | |
878 | ||
879 | # utility methods | |
880 | # note: this modifies the original hash by adding the id property | |
881 | sub hash_to_array { | |
882 | my ($hash, $idprop) = @_; | |
883 | ||
884 | my $res = []; | |
885 | return $res if !$hash; | |
886 | ||
887 | foreach my $k (keys %$hash) { | |
888 | $hash->{$k}->{$idprop} = $k; | |
889 | push @$res, $hash->{$k}; | |
890 | } | |
891 | ||
892 | return $res; | |
893 | } | |
894 | ||
895 | 1; |