1 package PVE
::RESTHandler
;
4 no strict
'refs'; # our autoload requires this
7 use PVE
::Exception
qw(raise raise_param_exc);
10 use HTTP
::Status
qw(:constants :is status_message);
14 my $method_registry = {};
15 my $method_by_name = {};
16 my $method_path_lookup = {};
18 our $AUTOLOAD; # it's a package global
20 our $standard_output_options = {
21 'output-format' => PVE
::JSONSchema
::get_standard_option
('pve-output-format'),
23 description
=> "Do not show column headers (for 'text' format).",
29 description
=> "Do not draw borders (for 'text' format).",
35 description
=> "Suppress printing results.",
40 description
=> "Call output rendering functions to produce human readable text.",
47 sub api_clone_schema
{
48 my ($schema, $no_typetext) = @_;
51 my $ref = ref($schema);
52 die "not a HASH reference" if !($ref && $ref eq 'HASH');
54 foreach my $k (keys %$schema) {
55 my $d = $schema->{$k};
56 if ($k ne 'properties') {
57 $res->{$k} = ref($d) ? clone
($d) : $d;
60 # convert indexed parameters like -net\d+ to -net[n]
61 foreach my $p (keys %$d) {
63 if ($p =~ m/^([a-z]+)(\d+)$/) {
64 my ($name, $idx) = ($1, $2);
65 if ($idx == 0 && defined($d->{"${name}1"})) {
67 } elsif ($idx > 0 && defined($d->{"${name}0"})) {
68 next; # only handle once for -xx0, but only if -xx0 exists
71 my $tmp = ref($pd) ? clone
($pd) : $pd;
72 # NOTE: add typetext property for complexer types, to make the web api-viewer code simpler
73 if (!$no_typetext && !(defined($tmp->{enum
}) || defined($tmp->{pattern
}))) {
74 my $typetext = PVE
::JSONSchema
::schema_get_type_text
($tmp);
75 if ($tmp->{type
} && ($tmp->{type
} ne $typetext)) {
76 $tmp->{typetext
} = $typetext;
79 $res->{$k}->{$p} = $tmp;
87 my ($tree, $index, $class, $prefix, $raw_dump) = @_;
89 $prefix = '' if !$prefix;
91 my $ma = $method_registry->{$class};
93 foreach my $info (@$ma) {
95 my $path = "$prefix/$info->{path}";
98 if ($info->{subclass
}) {
99 api_dump_full
($tree, $index, $info->{subclass
}, $path, $raw_dump);
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;
114 foreach my $dir (split('/', $path)) {
117 $res = (grep { $_->{text
} eq $dir } @$treedir)[0];
119 $res->{children
} = [] if !$res->{children
};
120 $treedir = $res->{children
};
127 push @$treedir, $res;
128 $treedir = $res->{children
};
134 foreach my $k (keys %$info) {
135 next if $k eq 'code' || $k eq "match_name" || $k eq "match_re" ||
143 if ($k eq 'parameters') {
144 $data->{$k} = api_clone_schema
($d);
145 } elsif ($k eq 'returns') {
146 $data->{$k} = api_clone_schema
($d, 1);
148 $data->{$k} = ref($d) ? clone
($d) : $d;
152 $res->{info
}->{$info->{method}} = $data;
158 sub api_dump_cleanup_tree
{
161 foreach my $rec (@$tree) {
162 delete $rec->{children
} if $rec->{children
} && !scalar(@{$rec->{children
}});
163 if ($rec->{children
}) {
165 api_dump_cleanup_tree
($rec->{children
});
173 # api_dump_remove_refs: prepare API tree for use with to_json($tree)
174 sub api_dump_remove_refs
{
177 my $class = ref($tree);
178 return $tree if !$class;
180 if ($class eq 'ARRAY') {
182 foreach my $el (@$tree) {
183 push @$res, api_dump_remove_refs
($el);
186 } elsif ($class eq 'HASH') {
188 foreach my $k (keys %$tree) {
189 if (my $itemclass = ref($tree->{$k})) {
190 if ($itemclass eq 'CODE') {
191 next if $k eq 'completion';
193 $res->{$k} = api_dump_remove_refs
($tree->{$k});
195 $res->{$k} = $tree->{$k};
199 } elsif ($class eq 'Regexp') {
200 return "$tree"; # return string representation
202 die "unknown class '$class'\n";
207 my ($class, $prefix, $raw_dump) = @_;
212 api_dump_full
($tree, $index, $class, $prefix, $raw_dump);
213 api_dump_cleanup_tree
($tree);
217 sub validate_method_schemas
{
219 foreach my $class (keys %$method_registry) {
220 my $ma = $method_registry->{$class};
222 foreach my $info (@$ma) {
223 PVE
::JSONSchema
::validate_method_info
($info);
228 sub register_method
{
229 my ($self, $info) = @_;
237 if ($info->{subclass
}) {
238 $errprefix = "register subclass $info->{subclass} at ${self}/$info->{path} -";
239 $method = 'SUBCLASS';
241 $errprefix = "register method ${self}/$info->{path} -";
242 $info->{method} = 'GET' if !$info->{method};
243 $method = $info->{method};
245 # apply default value
246 $info->{allowtoken
} = 1 if !defined($info->{allowtoken
});
249 $method_path_lookup->{$self} = {} if !defined($method_path_lookup->{$self});
250 my $path_lookup = $method_path_lookup->{$self};
252 die "$errprefix no path" if !defined($info->{path
});
254 foreach my $comp (split(/\/+/, $info->{path
})) {
255 die "$errprefix path compoment has zero length\n" if $comp eq '';
257 if ($comp =~ m/^\{([\w-]+)(?::(.*))?\}$/) {
259 $regex = $2 ?
$2 : '\S+';
260 push @$match_re, $regex;
261 push @$match_name, $name;
264 push @$match_re, $name;
265 push @$match_name, undef;
269 $path_lookup->{regex
} = {} if !defined($path_lookup->{regex
});
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;
280 die "$errprefix path match error - regex and fixed items\n"
281 if defined($path_lookup->{folders
});
283 $path_lookup = $path_lookup->{regex
};
286 $path_lookup->{folders
}->{$name} = {} if !defined($path_lookup->{folders
}->{$name});
288 die "$errprefix path match error - regex and fixed items\n"
289 if defined($path_lookup->{regex
});
291 $path_lookup = $path_lookup->{folders
}->{$name};
295 die "$errprefix duplicate method definition\n"
296 if defined($path_lookup->{$method});
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};
303 $path_lookup->{$method} = $info;
305 $info->{match_re
} = $match_re;
306 $info->{match_name
} = $match_name;
308 $method_by_name->{$self} = {} if !defined($method_by_name->{$self});
311 die "$errprefix method name already defined\n"
312 if defined($method_by_name->{$self}->{$info->{name
}});
314 $method_by_name->{$self}->{$info->{name
}} = $info;
317 push @{$method_registry->{$self}}, $info;
320 sub DESTROY
{}; # avoid problems with autoload
325 # also see "man perldiag"
328 (my $method = $sub) =~ s/.*:://;
330 my $info = $this->map_method_by_name($method);
334 return $self->handle($info, @_);
339 sub method_attributes
{
342 return $method_registry->{$self};
345 sub map_method_by_name
{
346 my ($self, $name) = @_;
348 my $info = $method_by_name->{$self}->{$name};
349 die "no such method '${self}::$name'\n" if !$info;
354 sub map_path_to_methods
{
355 my ($class, $stack, $uri_param, $pathmatchref) = @_;
357 my $path_lookup = $method_path_lookup->{$class};
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;
366 while (defined(my $comp = shift @$stack)) {
367 return undef if !$path_lookup; # not registerd?
368 if ($path_lookup->{regex
}) {
369 my $name = $path_lookup->{regex
}->{match_name
};
370 my $regex = $path_lookup->{regex
}->{match_re
};
372 return undef if $comp !~ m/^($regex)$/;
373 $uri_param->{$name} = $1;
374 $path_lookup = $path_lookup->{regex
};
375 $$pathmatchref .= '/{' . $name . '}' if defined($pathmatchref);
376 } elsif ($path_lookup->{folders
}) {
377 $path_lookup = $path_lookup->{folders
}->{$comp};
378 $$pathmatchref .= '/' . $comp if defined($pathmatchref);
380 die "internal error";
383 return undef if !$path_lookup;
385 if (my $info = $path_lookup->{SUBCLASS
}) {
386 $class = $info->{subclass
};
388 my $fd = $info->{fragmentDelimiter
};
391 # we only support the empty string '' (match whole URI)
392 die "unsupported fragmentDelimiter '$fd'"
395 $stack = [ join ('/', @$stack) ] if scalar(@$stack) > 1;
397 $path_lookup = $method_path_lookup->{$class};
401 return undef if !$path_lookup;
403 return ($class, $path_lookup);
407 my ($class, $method, $path, $uri_param, $pathmatchref) = @_;
409 my $stack = [ grep { length($_) > 0 } split('\/+' , $path)]; # skip empty fragments
411 my ($handler_class, $path_info);
413 ($handler_class, $path_info) = $class->map_path_to_methods($stack, $uri_param, $pathmatchref);
416 syslog
('err', $err) if $err;
418 return undef if !($handler_class && $path_info);
420 my $method_info = $path_info->{$method};
422 return undef if !$method_info;
424 return ($handler_class, $method_info);
428 my ($self, $info, $param, $result_verification) = @_;
430 my $func = $info->{code
};
432 if (!($info->{name
} && $func)) {
433 raise
("Method lookup failed ('$info->{name}')\n", code
=> HTTP_INTERNAL_SERVER_ERROR
);
436 if (my $schema = $info->{parameters
}) {
437 # warn "validate ". Dumper($param}) . "\n" . Dumper($schema);
438 PVE
::JSONSchema
::validate
($param, $schema);
439 # untaint data (already validated)
440 my $extra = delete $param->{'extra-args'};
441 while (my ($key, $val) = each %$param) {
443 ($param->{$key}) = $val =~ /^(.*)$/s;
445 $param->{$key} = undef;
448 $param->{'extra-args'} = [map { /^(.*)$/ } @$extra] if $extra;
451 my $result = $func->($param); # the actual API code execution call
453 if ($result_verification && (my $schema = $info->{returns
})) {
454 # return validation is rather lose-lose, as it can require quite a bit of time and lead to
455 # false-positive errors, any HTTP API handler should avoid enabling it by default.
456 PVE
::JSONSchema
::validate
($result, $schema, "Result verification failed\n");
461 # format option, display type and description
463 # $display_name: for example "-$name" of "<$name>", pass undef to use "$name:"
464 # $phash: json schema property hash
465 # $format: 'asciidoc', 'short', 'long' or 'full'
466 # $style: 'config', 'config-sub', 'arg' or 'fixed'
467 # $mapdef: parameter mapping ({ desc => XXX, func => sub {...} })
468 my $get_property_description = sub {
469 my ($name, $style, $phash, $format, $mapdef) = @_;
473 $format = 'asciidoc' if !defined($format);
475 my $descr = $phash->{description
} || "no description available";
477 if ($phash->{verbose_description
} &&
478 ($style eq 'config' || $style eq 'config-sub')) {
479 $descr = $phash->{verbose_description
};
484 my $type_text = PVE
::JSONSchema
::schema_get_type_text
($phash, $style);
486 if ($mapdef && $phash->{type
} eq 'string') {
487 $type_text = $mapdef->{desc
};
490 if ($format eq 'asciidoc') {
492 if ($style eq 'config') {
494 } elsif ($style eq 'config-sub') {
496 } elsif ($style eq 'arg') {
497 $res .= "`--$name` ";
498 } elsif ($style eq 'fixed') {
499 $res .= "`<$name>`: ";
501 die "unknown style '$style'";
504 $res .= "`$type_text` " if $type_text;
506 if (defined(my $dv = $phash->{default})) {
507 $res .= "('default =' `$dv`)";
510 if ($style eq 'config-sub') {
518 $wdescr =~ s/^$/+/mg;
520 $res .= $wdescr . "\n";
522 if (my $req = $phash->{requires
}) {
523 my $tmp .= ref($req) ?
join(', ', @$req) : $req;
524 $res .= "+\nNOTE: Requires option(s): `$tmp`\n";
528 } elsif ($format eq 'short' || $format eq 'long' || $format eq 'full') {
531 if (defined(my $dv = $phash->{default})) {
532 $defaulttxt = " (default=$dv)";
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>";
543 die "unknown style '$style'";
546 my $tmp = sprintf " %-10s %s%s\n", $display_name, "$type_text", "$defaulttxt";
549 $res .= Text
::Wrap
::wrap
('', $indend, ($tmp));
551 $res .= Text
::Wrap
::wrap
($indend, $indend, ($descr)) . "\n\n";
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";
560 die "unknown format '$format'";
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
573 # Returns: a hash indexed by parameter_name,
574 # i.e. { param_name => { func => .., desc => ... } }
575 my $compute_param_mapping_hash = sub {
576 my ($mapping_array) = @_;
580 return $res if !defined($mapping_array);
582 foreach my $item (@$mapping_array) {
583 my ($name, $func, $desc, $interactive);
584 if (ref($item) eq 'ARRAY') {
585 ($name, $func, $desc, $interactive) = @$item;
586 } elsif (ref($item) eq 'HASH') {
588 $res->{$item->{name
}} = $item;
592 $func = sub { return PVE
::Tools
::file_get_contents
($_[0]) };
594 $desc //= '<filepath>';
595 $res->{$name} = { desc
=> $desc, func
=> $func, interactive
=> $interactive };
601 # generate usage information for command line tools
603 # $info ... method info
604 # $prefix ... usually something like "$exename $cmd" ('pvesm add')
605 # $arg_param ... list of parameters we want to get as ordered arguments
606 # on the command line (or single parameter name for lists)
607 # $fixed_param ... do not generate and info about those parameters
609 # 'long' ... default (text, list all options)
610 # 'short' ... command line only (text, one line)
611 # 'full' ... text, include description
612 # 'asciidoc' ... generate asciidoc for man pages (like 'full')
613 # $param_cb ... mapping for string parameters to file path parameters
614 # $formatter_properties ... additional property definitions (passed to output formatter)
616 my ($info, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties) = @_;
618 $format = 'long' if !$format;
620 my $schema = $info->{parameters
};
621 my $name = $info->{name
};
623 if ($schema->{properties
}) {
624 $prop = { %{$schema->{properties
}} }; # copy
627 my $has_output_format_option = $formatter_properties->{'output-format'} ?
1 : 0;
629 if ($formatter_properties) {
630 foreach my $key (keys %$formatter_properties) {
631 if (!$standard_output_options->{$key}) {
632 $prop->{$key} = $formatter_properties->{$key};
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};
653 $arg_param = [ $arg_param ] if $arg_param && !ref($arg_param);
655 foreach my $p (@$arg_param) {
656 next if !$prop->{$p}; # just to be sure
657 my $pd = $prop->{$p};
660 $args .= " " if $args;
661 if ($pd->{format
} && $pd->{format
} =~ m/-list/) {
664 $args .= $pd->{optional
} ?
"[<$p>]" : "<$p>";
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
672 $argdescr .= $get_property_description->($k, 'fixed', $prop->{$k}, $format);
675 my $idx_param = {}; # -vlan\d+ -scsi\d+
678 foreach my $k (sort keys %$prop) {
679 next if $arg_hash->{$k};
680 next if defined($fixed_param->{$k});
682 my $type_text = $prop->{$k}->{type
} || 'string';
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
};
693 if ($k =~ m/^([a-z]+)(\d+)$/) {
694 my ($name, $idx) = ($1, $2);
695 next if $idx_param->{$name};
696 if ($idx == 0 && defined($prop->{"${name}1"})) {
697 $idx_param->{$name} = 1;
698 $base = "${name}[n]";
703 $opts .= $get_property_description->($base, 'arg', $prop->{$k}, $format, $param_map->{$k});
705 if (!$prop->{$k}->{optional
}) {
706 $args .= " " if $args;
707 $args .= "--$base <$type_text>"
711 if ($format eq 'asciidoc') {
712 $out .= "*${prefix}*";
713 $out .= " `$args`" if $args;
714 $out .= " `[OPTIONS]`" if $opts;
715 $out .= " `[FORMAT_OPTIONS]`" if $has_output_format_option;
718 $out .= "USAGE: " if $format ne 'short';
719 $out .= "$prefix $args";
720 $out .= " [OPTIONS]" if $opts;
721 $out .= " [FORMAT_OPTIONS]" if $has_output_format_option;
725 return $out if $format eq 'short';
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";
737 $out .= $argdescr if $argdescr;
739 $out .= $opts if $opts;
745 my ($self, $name, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties) = @_;
747 my $info = $self->map_method_by_name($name);
749 return getopt_usage
($info, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties);
752 # generate docs from JSON schema properties
753 sub dump_properties
{
754 my ($prop, $format, $style, $filterFn) = @_;
760 my $idx_param = {}; # -vlan\d+ -scsi\d+
762 foreach my $k (sort keys %$prop) {
763 my $phash = $prop->{$k};
765 next if defined($filterFn) && &$filterFn($k, $phash);
766 next if $phash->{alias
};
769 if ($k =~ m/^([a-z]+)(\d+)$/) {
770 my ($name, $idx) = ($1, $2);
771 next if $idx_param->{$name};
772 if ($idx == 0 && defined($prop->{"${name}1"})) {
773 $idx_param->{$name} = 1;
774 $base = "${name}[n]";
778 $raw .= $get_property_description->($base, $style, $phash, $format);
780 next if $style ne 'config';
782 my $prop_fmt = $phash->{format
};
785 if (ref($prop_fmt) ne 'HASH') {
786 $prop_fmt = PVE
::JSONSchema
::get_format
($prop_fmt);
789 next if !(ref($prop_fmt) && (ref($prop_fmt) eq 'HASH'));
791 $raw .= dump_properties
($prop_fmt, $format, 'config-sub')
798 my $replace_file_names_with_contents = sub {
799 my ($param, $param_map) = @_;
801 while (my ($k, $d) = each %$param_map) {
802 next if $d->{interactive
}; # handled by the JSONSchema's get_options code
803 $param->{$k} = $d->{func
}->($param->{$k})
804 if defined($param->{$k});
810 sub add_standard_output_properties
{
811 my ($propdef, $list) = @_;
815 $list //= [ keys %$standard_output_options ];
817 my $res = { %$propdef }; # copy
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};
828 sub extract_standard_output_properties
{
832 foreach my $opt (keys %$standard_output_options) {
833 $options->{$opt} = delete $data->{$opt} if defined($data->{$opt});
840 my ($self, $prefix, $name, $args, $arg_param, $fixed_param, $param_cb, $formatter_properties) = @_;
842 my $info = $self->map_method_by_name($name);
848 $param_map = $compute_param_mapping_hash->($param_cb->($name)) if $param_cb;
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);
853 if ($formatter_properties) {
854 foreach my $opt (keys %$formatter_properties) {
855 $fmt_param->{$opt} = delete $param->{$opt} if defined($param->{$opt});
859 if (defined($param_map)) {
860 $replace_file_names_with_contents->($param, $param_map);
863 $res = $self->handle($info, $param, 1);
868 die $err if !$ec || $ec ne "PVE::Exception" || !$err->is_param_exc();
870 $err->{usage
} = $self->usage_str($name, $prefix, $arg_param, $fixed_param, 'short', $param_cb, $formatter_properties);
875 return wantarray ?
($res, $fmt_param) : $res;
879 # note: this modifies the original hash by adding the id property
881 my ($hash, $idprop) = @_;
884 return $res if !$hash;
886 foreach my $k (keys %$hash) {
887 $hash->{$k}->{$idprop} = $k;
888 push @$res, $hash->{$k};