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 $wdescr =~ s/{/\\{/g;
521 $wdescr =~ s/}/\\}/g;
523 $res .= $wdescr . "\n";
525 if (my $req = $phash->{requires
}) {
526 my $tmp .= ref($req) ?
join(', ', @$req) : $req;
527 $res .= "+\nNOTE: Requires option(s): `$tmp`\n";
531 } elsif ($format eq 'short' || $format eq 'long' || $format eq 'full') {
534 if (defined(my $dv = $phash->{default})) {
535 $defaulttxt = " (default=$dv)";
539 if ($style eq 'config') {
540 $display_name = "$name:";
541 } elsif ($style eq 'arg') {
542 $display_name = "-$name";
543 } elsif ($style eq 'fixed') {
544 $display_name = "<$name>";
546 die "unknown style '$style'";
549 my $tmp = sprintf " %-10s %s%s\n", $display_name, "$type_text", "$defaulttxt";
552 $res .= Text
::Wrap
::wrap
('', $indend, ($tmp));
554 $res .= Text
::Wrap
::wrap
($indend, $indend, ($descr)) . "\n\n";
556 if (my $req = $phash->{requires
}) {
557 my $tmp = "Requires option(s): ";
558 $tmp .= ref($req) ?
join(', ', @$req) : $req;
559 $res .= Text
::Wrap
::wrap
($indend, $indend, ($tmp)). "\n\n";
563 die "unknown format '$format'";
569 # translate parameter mapping definition
570 # $mapping_array is a array which can contain:
571 # strings ... in that case we assume it is a parameter name, and
572 # we want to load that parameter from a file
573 # [ param_name, func, desc] ... allows you to specify a arbitrary
574 # mapping func for any param
576 # Returns: a hash indexed by parameter_name,
577 # i.e. { param_name => { func => .., desc => ... } }
578 my $compute_param_mapping_hash = sub {
579 my ($mapping_array) = @_;
583 return $res if !defined($mapping_array);
585 foreach my $item (@$mapping_array) {
586 my ($name, $func, $desc, $interactive);
587 if (ref($item) eq 'ARRAY') {
588 ($name, $func, $desc, $interactive) = @$item;
589 } elsif (ref($item) eq 'HASH') {
591 $res->{$item->{name
}} = $item;
595 $func = sub { return PVE
::Tools
::file_get_contents
($_[0]) };
597 $desc //= '<filepath>';
598 $res->{$name} = { desc
=> $desc, func
=> $func, interactive
=> $interactive };
604 # generate usage information for command line tools
606 # $info ... method info
607 # $prefix ... usually something like "$exename $cmd" ('pvesm add')
608 # $arg_param ... list of parameters we want to get as ordered arguments
609 # on the command line (or single parameter name for lists)
610 # $fixed_param ... do not generate and info about those parameters
612 # 'long' ... default (text, list all options)
613 # 'short' ... command line only (text, one line)
614 # 'full' ... text, include description
615 # 'asciidoc' ... generate asciidoc for man pages (like 'full')
616 # $param_cb ... mapping for string parameters to file path parameters
617 # $formatter_properties ... additional property definitions (passed to output formatter)
619 my ($info, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties) = @_;
621 $format = 'long' if !$format;
623 my $schema = $info->{parameters
};
624 my $name = $info->{name
};
626 if ($schema->{properties
}) {
627 $prop = { %{$schema->{properties
}} }; # copy
630 my $has_output_format_option = $formatter_properties->{'output-format'} ?
1 : 0;
632 if ($formatter_properties) {
633 foreach my $key (keys %$formatter_properties) {
634 if (!$standard_output_options->{$key}) {
635 $prop->{$key} = $formatter_properties->{$key};
640 # also remove $standard_output_options from $prop (pvesh, pveclient)
641 if ($prop->{'output-format'}) {
642 $has_output_format_option = 1;
643 foreach my $key (keys %$prop) {
644 if ($standard_output_options->{$key}) {
645 delete $prop->{$key};
656 $arg_param = [ $arg_param ] if $arg_param && !ref($arg_param);
658 foreach my $p (@$arg_param) {
659 next if !$prop->{$p}; # just to be sure
660 my $pd = $prop->{$p};
663 $args .= " " if $args;
664 if ($pd->{format
} && $pd->{format
} =~ m/-list/) {
667 $args .= $pd->{optional
} ?
"[<$p>]" : "<$p>";
672 foreach my $k (@$arg_param) {
673 next if defined($fixed_param->{$k}); # just to be sure
674 next if !$prop->{$k}; # just to be sure
675 $argdescr .= $get_property_description->($k, 'fixed', $prop->{$k}, $format);
678 my $idx_param = {}; # -vlan\d+ -scsi\d+
681 foreach my $k (sort keys %$prop) {
682 next if $arg_hash->{$k};
683 next if defined($fixed_param->{$k});
685 my $type_text = $prop->{$k}->{type
} || 'string';
689 if (defined($param_cb)) {
690 my $mapping = $param_cb->($name);
691 $param_map = $compute_param_mapping_hash->($mapping);
692 next if $k eq 'password' && $param_map->{$k} && !$prop->{$k}->{optional
};
696 if ($k =~ m/^([a-z]+)(\d+)$/) {
697 my ($name, $idx) = ($1, $2);
698 next if $idx_param->{$name};
699 if ($idx == 0 && defined($prop->{"${name}1"})) {
700 $idx_param->{$name} = 1;
701 $base = "${name}[n]";
706 $opts .= $get_property_description->($base, 'arg', $prop->{$k}, $format, $param_map->{$k});
708 if (!$prop->{$k}->{optional
}) {
709 $args .= " " if $args;
710 $args .= "--$base <$type_text>"
714 if ($format eq 'asciidoc') {
715 $out .= "*${prefix}*";
716 $out .= " `$args`" if $args;
717 $out .= " `[OPTIONS]`" if $opts;
718 $out .= " `[FORMAT_OPTIONS]`" if $has_output_format_option;
721 $out .= "USAGE: " if $format ne 'short';
722 $out .= "$prefix $args";
723 $out .= " [OPTIONS]" if $opts;
724 $out .= " [FORMAT_OPTIONS]" if $has_output_format_option;
728 return $out if $format eq 'short';
730 if ($info->{description
}) {
731 if ($format eq 'asciidoc') {
732 my $desc = Text
::Wrap
::wrap
('', '', ($info->{description
}));
733 $out .= "\n$desc\n\n";
734 } elsif ($format eq 'full') {
735 my $desc = Text
::Wrap
::wrap
(' ', ' ', ($info->{description
}));
736 $out .= "\n$desc\n\n";
740 $out .= $argdescr if $argdescr;
742 $out .= $opts if $opts;
748 my ($self, $name, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties) = @_;
750 my $info = $self->map_method_by_name($name);
752 return getopt_usage
($info, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties);
755 # generate docs from JSON schema properties
756 sub dump_properties
{
757 my ($prop, $format, $style, $filterFn) = @_;
763 my $idx_param = {}; # -vlan\d+ -scsi\d+
765 foreach my $k (sort keys %$prop) {
766 my $phash = $prop->{$k};
768 next if defined($filterFn) && &$filterFn($k, $phash);
769 next if $phash->{alias
};
772 if ($k =~ m/^([a-z]+)(\d+)$/) {
773 my ($name, $idx) = ($1, $2);
774 next if $idx_param->{$name};
775 if ($idx == 0 && defined($prop->{"${name}1"})) {
776 $idx_param->{$name} = 1;
777 $base = "${name}[n]";
781 $raw .= $get_property_description->($base, $style, $phash, $format);
783 next if $style ne 'config';
785 my $prop_fmt = $phash->{format
};
788 if (ref($prop_fmt) ne 'HASH') {
789 $prop_fmt = PVE
::JSONSchema
::get_format
($prop_fmt);
792 next if !(ref($prop_fmt) && (ref($prop_fmt) eq 'HASH'));
794 $raw .= dump_properties
($prop_fmt, $format, 'config-sub')
801 my $replace_file_names_with_contents = sub {
802 my ($param, $param_map) = @_;
804 while (my ($k, $d) = each %$param_map) {
805 next if $d->{interactive
}; # handled by the JSONSchema's get_options code
806 $param->{$k} = $d->{func
}->($param->{$k})
807 if defined($param->{$k});
813 sub add_standard_output_properties
{
814 my ($propdef, $list) = @_;
818 $list //= [ keys %$standard_output_options ];
820 my $res = { %$propdef }; # copy
822 foreach my $opt (@$list) {
823 die "no such standard output option '$opt'\n" if !defined($standard_output_options->{$opt});
824 die "detected overwriten standard CLI parameter '$opt'\n" if defined($res->{$opt});
825 $res->{$opt} = $standard_output_options->{$opt};
831 sub extract_standard_output_properties
{
835 foreach my $opt (keys %$standard_output_options) {
836 $options->{$opt} = delete $data->{$opt} if defined($data->{$opt});
843 my ($self, $prefix, $name, $args, $arg_param, $fixed_param, $param_cb, $formatter_properties) = @_;
845 my $info = $self->map_method_by_name($name);
851 $param_map = $compute_param_mapping_hash->($param_cb->($name)) if $param_cb;
852 my $schema = { %{$info->{parameters
}} }; # copy
853 $schema->{properties
} = { %{$schema->{properties
}}, %$formatter_properties } if $formatter_properties;
854 my $param = PVE
::JSONSchema
::get_options
($schema, $args, $arg_param, $fixed_param, $param_map);
856 if ($formatter_properties) {
857 foreach my $opt (keys %$formatter_properties) {
858 $fmt_param->{$opt} = delete $param->{$opt} if defined($param->{$opt});
862 if (defined($param_map)) {
863 $replace_file_names_with_contents->($param, $param_map);
866 $res = $self->handle($info, $param, 1);
871 die $err if !$ec || $ec ne "PVE::Exception" || !$err->is_param_exc();
873 $err->{usage
} = $self->usage_str($name, $prefix, $arg_param, $fixed_param, 'short', $param_cb, $formatter_properties);
878 return wantarray ?
($res, $fmt_param) : $res;
882 # note: this modifies the original hash by adding the id property
884 my ($hash, $idprop) = @_;
887 return $res if !$hash;
889 foreach my $k (keys %$hash) {
890 $hash->{$k}->{$idprop} = $k;
891 push @$res, $hash->{$k};