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};
247 $method_path_lookup->{$self} = {} if !defined($method_path_lookup->{$self});
248 my $path_lookup = $method_path_lookup->{$self};
250 die "$errprefix no path" if !defined($info->{path
});
252 foreach my $comp (split(/\/+/, $info->{path
})) {
253 die "$errprefix path compoment has zero length\n" if $comp eq '';
255 if ($comp =~ m/^\{(\w+)(:(.*))?\}$/) {
257 $regex = $3 ?
$3 : '\S+';
258 push @$match_re, $regex;
259 push @$match_name, $name;
262 push @$match_re, $name;
263 push @$match_name, undef;
267 $path_lookup->{regex
} = {} if !defined($path_lookup->{regex
});
269 my $old_name = $path_lookup->{regex
}->{match_name
};
270 die "$errprefix found changed regex match name\n"
271 if defined($old_name) && ($old_name ne $name);
272 my $old_re = $path_lookup->{regex
}->{match_re
};
273 die "$errprefix found changed regex\n"
274 if defined($old_re) && ($old_re ne $regex);
275 $path_lookup->{regex
}->{match_name
} = $name;
276 $path_lookup->{regex
}->{match_re
} = $regex;
278 die "$errprefix path match error - regex and fixed items\n"
279 if defined($path_lookup->{folders
});
281 $path_lookup = $path_lookup->{regex
};
284 $path_lookup->{folders
}->{$name} = {} if !defined($path_lookup->{folders
}->{$name});
286 die "$errprefix path match error - regex and fixed items\n"
287 if defined($path_lookup->{regex
});
289 $path_lookup = $path_lookup->{folders
}->{$name};
293 die "$errprefix duplicate method definition\n"
294 if defined($path_lookup->{$method});
296 if ($method eq 'SUBCLASS') {
297 foreach my $m (qw(GET PUT POST DELETE)) {
298 die "$errprefix duplicate method definition SUBCLASS and $m\n" if $path_lookup->{$m};
301 $path_lookup->{$method} = $info;
303 $info->{match_re
} = $match_re;
304 $info->{match_name
} = $match_name;
306 $method_by_name->{$self} = {} if !defined($method_by_name->{$self});
309 die "$errprefix method name already defined\n"
310 if defined($method_by_name->{$self}->{$info->{name
}});
312 $method_by_name->{$self}->{$info->{name
}} = $info;
315 push @{$method_registry->{$self}}, $info;
318 sub DESTROY
{}; # avoid problems with autoload
323 # also see "man perldiag"
326 (my $method = $sub) =~ s/.*:://;
328 my $info = $this->map_method_by_name($method);
332 return $self->handle($info, @_);
337 sub method_attributes
{
340 return $method_registry->{$self};
343 sub map_method_by_name
{
344 my ($self, $name) = @_;
346 my $info = $method_by_name->{$self}->{$name};
347 die "no such method '${self}::$name'\n" if !$info;
352 sub map_path_to_methods
{
353 my ($class, $stack, $uri_param, $pathmatchref) = @_;
355 my $path_lookup = $method_path_lookup->{$class};
357 # Note: $pathmatchref can be used to obtain path including
358 # uri patterns like '/cluster/firewall/groups/{group}'.
359 # Used by pvesh to display help
360 if (defined($pathmatchref)) {
361 $$pathmatchref = '' if !$$pathmatchref;
364 while (defined(my $comp = shift @$stack)) {
365 return undef if !$path_lookup; # not registerd?
366 if ($path_lookup->{regex
}) {
367 my $name = $path_lookup->{regex
}->{match_name
};
368 my $regex = $path_lookup->{regex
}->{match_re
};
370 return undef if $comp !~ m/^($regex)$/;
371 $uri_param->{$name} = $1;
372 $path_lookup = $path_lookup->{regex
};
373 $$pathmatchref .= '/{' . $name . '}' if defined($pathmatchref);
374 } elsif ($path_lookup->{folders
}) {
375 $path_lookup = $path_lookup->{folders
}->{$comp};
376 $$pathmatchref .= '/' . $comp if defined($pathmatchref);
378 die "internal error";
381 return undef if !$path_lookup;
383 if (my $info = $path_lookup->{SUBCLASS
}) {
384 $class = $info->{subclass
};
386 my $fd = $info->{fragmentDelimiter
};
389 # we only support the empty string '' (match whole URI)
390 die "unsupported fragmentDelimiter '$fd'"
393 $stack = [ join ('/', @$stack) ] if scalar(@$stack) > 1;
395 $path_lookup = $method_path_lookup->{$class};
399 return undef if !$path_lookup;
401 return ($class, $path_lookup);
405 my ($class, $method, $path, $uri_param, $pathmatchref) = @_;
407 my $stack = [ grep { length($_) > 0 } split('\/+' , $path)]; # skip empty fragments
409 my ($handler_class, $path_info);
411 ($handler_class, $path_info) = $class->map_path_to_methods($stack, $uri_param, $pathmatchref);
414 syslog
('err', $err) if $err;
416 return undef if !($handler_class && $path_info);
418 my $method_info = $path_info->{$method};
420 return undef if !$method_info;
422 return ($handler_class, $method_info);
426 my ($self, $info, $param) = @_;
428 my $func = $info->{code
};
430 if (!($info->{name
} && $func)) {
431 raise
("Method lookup failed ('$info->{name}')\n",
432 code
=> HTTP_INTERNAL_SERVER_ERROR
);
435 if (my $schema = $info->{parameters
}) {
436 # warn "validate ". Dumper($param}) . "\n" . Dumper($schema);
437 PVE
::JSONSchema
::validate
($param, $schema);
438 # untaint data (already validated)
439 my $extra = delete $param->{'extra-args'};
440 while (my ($key, $val) = each %$param) {
441 ($param->{$key}) = $val =~ /^(.*)$/s;
443 $param->{'extra-args'} = [map { /^(.*)$/ } @$extra] if $extra;
446 my $result = &$func($param);
448 # todo: this is only to be safe - disable?
449 if (my $schema = $info->{returns
}) {
450 PVE
::JSONSchema
::validate
($result, $schema, "Result verification failed\n");
456 # format option, display type and description
458 # $display_name: for example "-$name" of "<$name>", pass undef to use "$name:"
459 # $phash: json schema property hash
460 # $format: 'asciidoc', 'short', 'long' or 'full'
461 # $style: 'config', 'config-sub', 'arg' or 'fixed'
462 # $mapdef: parameter mapping ({ desc => XXX, func => sub {...} })
463 my $get_property_description = sub {
464 my ($name, $style, $phash, $format, $mapdef) = @_;
468 $format = 'asciidoc' if !defined($format);
470 my $descr = $phash->{description
} || "no description available";
472 if ($phash->{verbose_description
} &&
473 ($style eq 'config' || $style eq 'config-sub')) {
474 $descr = $phash->{verbose_description
};
479 my $type_text = PVE
::JSONSchema
::schema_get_type_text
($phash, $style);
481 if ($mapdef && $phash->{type
} eq 'string') {
482 $type_text = $mapdef->{desc
};
485 if ($format eq 'asciidoc') {
487 if ($style eq 'config') {
489 } elsif ($style eq 'config-sub') {
491 } elsif ($style eq 'arg') {
492 $res .= "`--$name` ";
493 } elsif ($style eq 'fixed') {
494 $res .= "`<$name>`: ";
496 die "unknown style '$style'";
499 $res .= "`$type_text` " if $type_text;
501 if (defined(my $dv = $phash->{default})) {
502 $res .= "('default =' `$dv`)";
505 if ($style eq 'config-sub') {
513 $wdescr =~ s/^$/+/mg;
515 $res .= $wdescr . "\n";
517 if (my $req = $phash->{requires
}) {
518 my $tmp .= ref($req) ?
join(', ', @$req) : $req;
519 $res .= "+\nNOTE: Requires option(s): `$tmp`\n";
523 } elsif ($format eq 'short' || $format eq 'long' || $format eq 'full') {
526 if (defined(my $dv = $phash->{default})) {
527 $defaulttxt = " (default=$dv)";
531 if ($style eq 'config') {
532 $display_name = "$name:";
533 } elsif ($style eq 'arg') {
534 $display_name = "-$name";
535 } elsif ($style eq 'fixed') {
536 $display_name = "<$name>";
538 die "unknown style '$style'";
541 my $tmp = sprintf " %-10s %s$defaulttxt\n", $display_name, "$type_text";
544 $res .= Text
::Wrap
::wrap
('', $indend, ($tmp));
546 $res .= Text
::Wrap
::wrap
($indend, $indend, ($descr)) . "\n\n";
548 if (my $req = $phash->{requires
}) {
549 my $tmp = "Requires option(s): ";
550 $tmp .= ref($req) ?
join(', ', @$req) : $req;
551 $res .= Text
::Wrap
::wrap
($indend, $indend, ($tmp)). "\n\n";
555 die "unknown format '$format'";
561 # translate parameter mapping definition
562 # $mapping_array is a array which can contain:
563 # strings ... in that case we assume it is a parameter name, and
564 # we want to load that parameter from a file
565 # [ param_name, func, desc] ... allows you to specify a arbitrary
566 # mapping func for any param
568 # Returns: a hash indexed by parameter_name,
569 # i.e. { param_name => { func => .., desc => ... } }
570 my $compute_param_mapping_hash = sub {
571 my ($mapping_array) = @_;
575 return $res if !defined($mapping_array);
577 foreach my $item (@$mapping_array) {
578 my ($name, $func, $desc, $interactive);
579 if (ref($item) eq 'ARRAY') {
580 ($name, $func, $desc, $interactive) = @$item;
581 } elsif (ref($item) eq 'HASH') {
583 $res->{$item->{name
}} = $item;
587 $func = sub { return PVE
::Tools
::file_get_contents
($_[0]) };
589 $desc //= '<filepath>';
590 $res->{$name} = { desc
=> $desc, func
=> $func, interactive
=> $interactive };
596 # generate usage information for command line tools
598 # $info ... method info
599 # $prefix ... usually something like "$exename $cmd" ('pvesm add')
600 # $arg_param ... list of parameters we want to get as ordered arguments
601 # on the command line (or single parameter name for lists)
602 # $fixed_param ... do not generate and info about those parameters
604 # 'long' ... default (text, list all options)
605 # 'short' ... command line only (text, one line)
606 # 'full' ... text, include description
607 # 'asciidoc' ... generate asciidoc for man pages (like 'full')
608 # $param_cb ... mapping for string parameters to file path parameters
609 # $formatter_properties ... additional property definitions (passed to output formatter)
611 my ($info, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties) = @_;
613 $format = 'long' if !$format;
615 my $schema = $info->{parameters
};
616 my $name = $info->{name
};
617 my $prop = { %{$schema->{properties
}} }; # copy
619 my $has_output_format_option = $formatter_properties->{'output-format'} ?
1 : 0;
621 if ($formatter_properties) {
622 foreach my $key (keys %$formatter_properties) {
623 if (!$standard_output_options->{$key}) {
624 $prop->{$key} = $formatter_properties->{$key};
629 # also remove $standard_output_options from $prop (pvesh, pveclient)
630 if ($prop->{'output-format'}) {
631 $has_output_format_option = 1;
632 foreach my $key (keys %$prop) {
633 if ($standard_output_options->{$key}) {
634 delete $prop->{$key};
645 $arg_param = [ $arg_param ] if $arg_param && !ref($arg_param);
647 foreach my $p (@$arg_param) {
648 next if !$prop->{$p}; # just to be sure
649 my $pd = $prop->{$p};
652 $args .= " " if $args;
653 if ($pd->{format
} && $pd->{format
} =~ m/-list/) {
656 $args .= $pd->{optional
} ?
"[<$p>]" : "<$p>";
661 foreach my $k (@$arg_param) {
662 next if defined($fixed_param->{$k}); # just to be sure
663 next if !$prop->{$k}; # just to be sure
664 $argdescr .= $get_property_description->($k, 'fixed', $prop->{$k}, $format);
667 my $idx_param = {}; # -vlan\d+ -scsi\d+
670 foreach my $k (sort keys %$prop) {
671 next if $arg_hash->{$k};
672 next if defined($fixed_param->{$k});
674 my $type_text = $prop->{$k}->{type
} || 'string';
678 if (defined($param_cb)) {
679 my $mapping = $param_cb->($name);
680 $param_map = $compute_param_mapping_hash->($mapping);
681 next if $k eq 'password' && $param_map->{$k} && !$prop->{$k}->{optional
};
685 if ($k =~ m/^([a-z]+)(\d+)$/) {
686 my ($name, $idx) = ($1, $2);
687 next if $idx_param->{$name};
688 if ($idx == 0 && defined($prop->{"${name}1"})) {
689 $idx_param->{$name} = 1;
690 $base = "${name}[n]";
695 $opts .= $get_property_description->($base, 'arg', $prop->{$k}, $format, $param_map->{$k});
697 if (!$prop->{$k}->{optional
}) {
698 $args .= " " if $args;
699 $args .= "--$base <$type_text>"
703 if ($format eq 'asciidoc') {
704 $out .= "*${prefix}*";
705 $out .= " `$args`" if $args;
706 $out .= " `[OPTIONS]`" if $opts;
707 $out .= " `[FORMAT_OPTIONS]`" if $has_output_format_option;
710 $out .= "USAGE: " if $format ne 'short';
711 $out .= "$prefix $args";
712 $out .= " [OPTIONS]" if $opts;
713 $out .= " [FORMAT_OPTIONS]" if $has_output_format_option;
717 return $out if $format eq 'short';
719 if ($info->{description
}) {
720 if ($format eq 'asciidoc') {
721 my $desc = Text
::Wrap
::wrap
('', '', ($info->{description
}));
722 $out .= "\n$desc\n\n";
723 } elsif ($format eq 'full') {
724 my $desc = Text
::Wrap
::wrap
(' ', ' ', ($info->{description
}));
725 $out .= "\n$desc\n\n";
729 $out .= $argdescr if $argdescr;
731 $out .= $opts if $opts;
737 my ($self, $name, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties) = @_;
739 my $info = $self->map_method_by_name($name);
741 return getopt_usage
($info, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties);
744 # generate docs from JSON schema properties
745 sub dump_properties
{
746 my ($prop, $format, $style, $filterFn) = @_;
752 my $idx_param = {}; # -vlan\d+ -scsi\d+
754 foreach my $k (sort keys %$prop) {
755 my $phash = $prop->{$k};
757 next if defined($filterFn) && &$filterFn($k, $phash);
758 next if $phash->{alias
};
761 if ($k =~ m/^([a-z]+)(\d+)$/) {
762 my ($name, $idx) = ($1, $2);
763 next if $idx_param->{$name};
764 if ($idx == 0 && defined($prop->{"${name}1"})) {
765 $idx_param->{$name} = 1;
766 $base = "${name}[n]";
770 $raw .= $get_property_description->($base, $style, $phash, $format);
772 next if $style ne 'config';
774 my $prop_fmt = $phash->{format
};
777 if (ref($prop_fmt) ne 'HASH') {
778 $prop_fmt = PVE
::JSONSchema
::get_format
($prop_fmt);
781 next if !(ref($prop_fmt) && (ref($prop_fmt) eq 'HASH'));
783 $raw .= dump_properties
($prop_fmt, $format, 'config-sub')
790 my $replace_file_names_with_contents = sub {
791 my ($param, $param_map) = @_;
793 while (my ($k, $d) = each %$param_map) {
794 next if $d->{interactive
}; # handled by the JSONSchema's get_options code
795 $param->{$k} = $d->{func
}->($param->{$k})
796 if defined($param->{$k});
802 sub add_standard_output_properties
{
803 my ($propdef, $list) = @_;
807 $list //= [ keys %$standard_output_options ];
809 my $res = { %$propdef }; # copy
811 foreach my $opt (@$list) {
812 die "no such standard output option '$opt'\n" if !defined($standard_output_options->{$opt});
813 die "detected overwriten standard CLI parameter '$opt'\n" if defined($res->{$opt});
814 $res->{$opt} = $standard_output_options->{$opt};
820 sub extract_standard_output_properties
{
824 foreach my $opt (keys %$standard_output_options) {
825 $options->{$opt} = delete $data->{$opt} if defined($data->{$opt});
832 my ($self, $prefix, $name, $args, $arg_param, $fixed_param, $param_cb, $formatter_properties) = @_;
834 my $info = $self->map_method_by_name($name);
840 $param_map = $compute_param_mapping_hash->($param_cb->($name)) if $param_cb;
841 my $schema = { %{$info->{parameters
}} }; # copy
842 $schema->{properties
} = { %{$schema->{properties
}}, %$formatter_properties } if $formatter_properties;
843 my $param = PVE
::JSONSchema
::get_options
($schema, $args, $arg_param, $fixed_param, $param_map);
845 if ($formatter_properties) {
846 foreach my $opt (keys %$formatter_properties) {
847 $fmt_param->{$opt} = delete $param->{$opt} if defined($param->{$opt});
851 if (defined($param_map)) {
852 $replace_file_names_with_contents->($param, $param_map);
855 $res = $self->handle($info, $param);
860 die $err if !$ec || $ec ne "PVE::Exception" || !$err->is_param_exc();
862 $err->{usage
} = $self->usage_str($name, $prefix, $arg_param, $fixed_param, 'short', $param_cb, $formatter_properties);
867 return wantarray ?
($res, $fmt_param) : $res;
871 # note: this modifies the original hash by adding the id property
873 my ($hash, $idprop) = @_;
876 return $res if !$hash;
878 foreach my $k (keys %$hash) {
879 $hash->{$k}->{$idprop} = $k;
880 push @$res, $hash->{$k};