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 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;
80 $res->{$k}->{$p} = $tmp;
88 my ($tree, $index, $class, $prefix, $raw_dump) = @_;
90 $prefix = '' if !$prefix;
92 my $ma = $method_registry->{$class};
94 foreach my $info (@$ma) {
96 my $path = "$prefix/$info->{path}";
99 if ($info->{subclass
}) {
100 api_dump_full
($tree, $index, $info->{subclass
}, $path, $raw_dump);
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;
115 foreach my $dir (split('/', $path)) {
118 $res = (grep { $_->{text
} eq $dir } @$treedir)[0];
120 $res->{children
} = [] if !$res->{children
};
121 $treedir = $res->{children
};
128 push @$treedir, $res;
129 $treedir = $res->{children
};
135 foreach my $k (keys %$info) {
136 next if $k eq 'code' || $k eq "match_name" || $k eq "match_re" ||
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);
149 $data->{$k} = ref($d) ? clone
($d) : $d;
153 $res->{info
}->{$info->{method}} = $data;
159 sub api_dump_cleanup_tree
{
162 foreach my $rec (@$tree) {
163 delete $rec->{children
} if $rec->{children
} && !scalar(@{$rec->{children
}});
164 if ($rec->{children
}) {
166 api_dump_cleanup_tree
($rec->{children
});
174 # api_dump_remove_refs: prepare API tree for use with to_json($tree)
175 sub api_dump_remove_refs
{
178 my $class = ref($tree);
179 return $tree if !$class;
181 if ($class eq 'ARRAY') {
183 foreach my $el (@$tree) {
184 push @$res, api_dump_remove_refs
($el);
187 } elsif ($class eq 'HASH') {
189 foreach my $k (keys %$tree) {
190 if (my $itemclass = ref($tree->{$k})) {
191 if ($itemclass eq 'CODE') {
192 next if $k eq 'completion';
194 $res->{$k} = api_dump_remove_refs
($tree->{$k});
196 $res->{$k} = $tree->{$k};
200 } elsif ($class eq 'Regexp') {
201 return "$tree"; # return string representation
203 die "unknown class '$class'\n";
208 my ($class, $prefix, $raw_dump) = @_;
213 api_dump_full
($tree, $index, $class, $prefix, $raw_dump);
214 api_dump_cleanup_tree
($tree);
218 sub validate_method_schemas
{
220 foreach my $class (keys %$method_registry) {
221 my $ma = $method_registry->{$class};
223 foreach my $info (@$ma) {
224 PVE
::JSONSchema
::validate_method_info
($info);
229 sub register_method
{
230 my ($self, $info) = @_;
238 if ($info->{subclass
}) {
239 $errprefix = "register subclass $info->{subclass} at ${self}/$info->{path} -";
240 $method = 'SUBCLASS';
242 $errprefix = "register method ${self}/$info->{path} -";
243 $info->{method} = 'GET' if !$info->{method};
244 $method = $info->{method};
246 # apply default value
247 $info->{allowtoken
} = 1 if !defined($info->{allowtoken
});
250 $method_path_lookup->{$self} = {} if !defined($method_path_lookup->{$self});
251 my $path_lookup = $method_path_lookup->{$self};
253 die "$errprefix no path" if !defined($info->{path
});
255 foreach my $comp (split(/\/+/, $info->{path
})) {
256 die "$errprefix path compoment has zero length\n" if $comp eq '';
258 if ($comp =~ m/^\{([\w-]+)(?::(.*))?\}$/) {
260 $regex = $2 ?
$2 : '\S+';
261 push @$match_re, $regex;
262 push @$match_name, $name;
265 push @$match_re, $name;
266 push @$match_name, undef;
270 $path_lookup->{regex
} = {} if !defined($path_lookup->{regex
});
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;
281 die "$errprefix path match error - regex and fixed items\n"
282 if defined($path_lookup->{folders
});
284 $path_lookup = $path_lookup->{regex
};
287 $path_lookup->{folders
}->{$name} = {} if !defined($path_lookup->{folders
}->{$name});
289 die "$errprefix path match error - regex and fixed items\n"
290 if defined($path_lookup->{regex
});
292 $path_lookup = $path_lookup->{folders
}->{$name};
296 die "$errprefix duplicate method definition\n"
297 if defined($path_lookup->{$method});
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};
304 $path_lookup->{$method} = $info;
306 $info->{match_re
} = $match_re;
307 $info->{match_name
} = $match_name;
309 $method_by_name->{$self} = {} if !defined($method_by_name->{$self});
312 die "$errprefix method name already defined\n"
313 if defined($method_by_name->{$self}->{$info->{name
}});
315 $method_by_name->{$self}->{$info->{name
}} = $info;
318 push @{$method_registry->{$self}}, $info;
321 sub DESTROY
{}; # avoid problems with autoload
326 # also see "man perldiag"
329 (my $method = $sub) =~ s/.*:://;
331 my $info = $this->map_method_by_name($method);
335 return $self->handle($info, @_);
340 sub method_attributes
{
343 return $method_registry->{$self};
346 sub map_method_by_name
{
347 my ($self, $name) = @_;
349 my $info = $method_by_name->{$self}->{$name};
350 die "no such method '${self}::$name'\n" if !$info;
355 sub map_path_to_methods
{
356 my ($class, $stack, $uri_param, $pathmatchref) = @_;
358 my $path_lookup = $method_path_lookup->{$class};
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;
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
};
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);
381 die "internal error";
384 return undef if !$path_lookup;
386 if (my $info = $path_lookup->{SUBCLASS
}) {
387 $class = $info->{subclass
};
389 my $fd = $info->{fragmentDelimiter
};
392 # we only support the empty string '' (match whole URI)
393 die "unsupported fragmentDelimiter '$fd'"
396 $stack = [ join ('/', @$stack) ] if scalar(@$stack) > 1;
398 $path_lookup = $method_path_lookup->{$class};
402 return undef if !$path_lookup;
404 return ($class, $path_lookup);
408 my ($class, $method, $path, $uri_param, $pathmatchref) = @_;
410 my $stack = [ grep { length($_) > 0 } split('\/+' , $path)]; # skip empty fragments
412 my ($handler_class, $path_info);
414 ($handler_class, $path_info) = $class->map_path_to_methods($stack, $uri_param, $pathmatchref);
417 syslog
('err', $err) if $err;
419 return undef if !($handler_class && $path_info);
421 my $method_info = $path_info->{$method};
423 return undef if !$method_info;
425 return ($handler_class, $method_info);
429 my ($self, $info, $param, $result_verification) = @_;
431 my $func = $info->{code
};
433 if (!($info->{name
} && $func)) {
434 raise
("Method lookup failed ('$info->{name}')\n", code
=> HTTP_INTERNAL_SERVER_ERROR
);
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) {
444 ($param->{$key}) = $val =~ /^(.*)$/s;
446 $param->{$key} = undef;
449 $param->{'extra-args'} = [map { /^(.*)$/ } @$extra] if $extra;
452 my $result = $func->($param); # the actual API code execution call
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");
462 # format option, display type and description
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) = @_;
474 $format = 'asciidoc' if !defined($format);
476 my $descr = $phash->{description
} || "no description available";
478 if ($phash->{verbose_description
} &&
479 ($style eq 'config' || $style eq 'config-sub')) {
480 $descr = $phash->{verbose_description
};
485 my $type_text = PVE
::JSONSchema
::schema_get_type_text
($phash, $style);
487 if ($mapdef && $phash->{type
} eq 'string') {
488 $type_text = $mapdef->{desc
};
491 if ($format eq 'asciidoc') {
493 if ($style eq 'config') {
495 } elsif ($style eq 'config-sub') {
497 } elsif ($style eq 'arg') {
498 $res .= "`--$name` ";
499 } elsif ($style eq 'fixed') {
500 $res .= "`<$name>`: ";
502 die "unknown style '$style'";
505 $res .= "`$type_text` " if $type_text;
507 if (defined(my $dv = $phash->{default})) {
508 $res .= "('default =' `$dv`)";
511 if ($style eq 'config-sub') {
519 $wdescr =~ s/^$/+/mg;
521 $res .= $wdescr . "\n";
523 if (my $req = $phash->{requires
}) {
524 my $tmp .= ref($req) ?
join(', ', @$req) : $req;
525 $res .= "+\nNOTE: Requires option(s): `$tmp`\n";
529 } elsif ($format eq 'short' || $format eq 'long' || $format eq 'full') {
532 if (defined(my $dv = $phash->{default})) {
533 $defaulttxt = " (default=$dv)";
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>";
544 die "unknown style '$style'";
547 my $tmp = sprintf " %-10s %s%s\n", $display_name, "$type_text", "$defaulttxt";
550 $res .= Text
::Wrap
::wrap
('', $indend, ($tmp));
552 $res .= Text
::Wrap
::wrap
($indend, $indend, ($descr)) . "\n\n";
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";
561 die "unknown format '$format'";
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
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) = @_;
581 return $res if !defined($mapping_array);
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') {
589 $res->{$item->{name
}} = $item;
593 $func = sub { return PVE
::Tools
::file_get_contents
($_[0]) };
595 $desc //= '<filepath>';
596 $res->{$name} = { desc
=> $desc, func
=> $func, interactive
=> $interactive };
602 # generate usage information for command line tools
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
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)
617 my ($info, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties) = @_;
619 $format = 'long' if !$format;
621 my $schema = $info->{parameters
};
622 my $name = $info->{name
};
624 if ($schema->{properties
}) {
625 $prop = { %{$schema->{properties
}} }; # copy
628 my $has_output_format_option = $formatter_properties->{'output-format'} ?
1 : 0;
630 if ($formatter_properties) {
631 foreach my $key (keys %$formatter_properties) {
632 if (!$standard_output_options->{$key}) {
633 $prop->{$key} = $formatter_properties->{$key};
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};
654 $arg_param = [ $arg_param ] if $arg_param && !ref($arg_param);
656 foreach my $p (@$arg_param) {
657 next if !$prop->{$p}; # just to be sure
658 my $pd = $prop->{$p};
661 $args .= " " if $args;
662 if ($pd->{format
} && $pd->{format
} =~ m/-list/) {
665 $args .= $pd->{optional
} ?
"[<$p>]" : "<$p>";
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);
676 my $idx_param = {}; # -vlan\d+ -scsi\d+
679 foreach my $k (sort keys %$prop) {
680 next if $arg_hash->{$k};
681 next if defined($fixed_param->{$k});
683 my $type_text = $prop->{$k}->{type
} || 'string';
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
};
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]";
704 $opts .= $get_property_description->($base, 'arg', $prop->{$k}, $format, $param_map->{$k});
706 if (!$prop->{$k}->{optional
}) {
707 $args .= " " if $args;
708 $args .= "--$base <$type_text>"
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;
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;
726 return $out if $format eq 'short';
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";
738 $out .= $argdescr if $argdescr;
740 $out .= $opts if $opts;
746 my ($self, $name, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties) = @_;
748 my $info = $self->map_method_by_name($name);
750 return getopt_usage
($info, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties);
753 # generate docs from JSON schema properties
754 sub dump_properties
{
755 my ($prop, $format, $style, $filterFn) = @_;
761 my $idx_param = {}; # -vlan\d+ -scsi\d+
763 foreach my $k (sort keys %$prop) {
764 my $phash = $prop->{$k};
766 next if defined($filterFn) && &$filterFn($k, $phash);
767 next if $phash->{alias
};
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]";
779 $raw .= $get_property_description->($base, $style, $phash, $format);
781 next if $style ne 'config';
783 my $prop_fmt = $phash->{format
};
786 if (ref($prop_fmt) ne 'HASH') {
787 $prop_fmt = PVE
::JSONSchema
::get_format
($prop_fmt);
790 next if !(ref($prop_fmt) && (ref($prop_fmt) eq 'HASH'));
792 $raw .= dump_properties
($prop_fmt, $format, 'config-sub')
799 my $replace_file_names_with_contents = sub {
800 my ($param, $param_map) = @_;
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});
811 sub add_standard_output_properties
{
812 my ($propdef, $list) = @_;
816 $list //= [ keys %$standard_output_options ];
818 my $res = { %$propdef }; # copy
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};
829 sub extract_standard_output_properties
{
833 foreach my $opt (keys %$standard_output_options) {
834 $options->{$opt} = delete $data->{$opt} if defined($data->{$opt});
841 my ($self, $prefix, $name, $args, $arg_param, $fixed_param, $param_cb, $formatter_properties) = @_;
843 my $info = $self->map_method_by_name($name);
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);
854 if ($formatter_properties) {
855 foreach my $opt (keys %$formatter_properties) {
856 $fmt_param->{$opt} = delete $param->{$opt} if defined($param->{$opt});
860 if (defined($param_map)) {
861 $replace_file_names_with_contents->($param, $param_map);
864 $res = $self->handle($info, $param, 1);
869 die $err if !$ec || $ec ne "PVE::Exception" || !$err->is_param_exc();
871 $err->{usage
} = $self->usage_str($name, $prefix, $arg_param, $fixed_param, 'short', $param_cb, $formatter_properties);
876 return wantarray ?
($res, $fmt_param) : $res;
880 # note: this modifies the original hash by adding the id property
882 my ($hash, $idprop) = @_;
885 return $res if !$hash;
887 foreach my $k (keys %$hash) {
888 $hash->{$k}->{$idprop} = $k;
889 push @$res, $hash->{$k};