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 sub api_clone_schema
{
24 my $ref = ref($schema);
25 die "not a HASH reference" if !($ref && $ref eq 'HASH');
27 foreach my $k (keys %$schema) {
28 my $d = $schema->{$k};
29 if ($k ne 'properties') {
30 $res->{$k} = ref($d) ? clone
($d) : $d;
33 # convert indexed parameters like -net\d+ to -net[n]
34 foreach my $p (keys %$d) {
36 if ($p =~ m/^([a-z]+)(\d+)$/) {
37 my ($name, $idx) = ($1, $2);
38 if ($idx == 0 && defined($d->{"${name}1"})) {
40 } elsif (defined($d->{"${name}0"})) {
41 next; # only handle once for -xx0, but only if -xx0 exists
44 my $tmp = ref($pd) ? clone
($pd) : $pd;
45 # NOTE: add typetext property for more complex types, to
46 # make the web api viewer code simpler
47 if (!(defined($tmp->{enum
}) || defined($tmp->{pattern
}))) {
48 my $typetext = PVE
::JSONSchema
::schema_get_type_text
($tmp);
49 if ($tmp->{type
} && ($tmp->{type
} ne $typetext)) {
50 $tmp->{typetext
} = $typetext;
53 $res->{$k}->{$p} = $tmp;
61 my ($tree, $index, $class, $prefix) = @_;
63 $prefix = '' if !$prefix;
65 my $ma = $method_registry->{$class};
67 foreach my $info (@$ma) {
69 my $path = "$prefix/$info->{path}";
72 if ($info->{subclass
}) {
73 api_dump_full
($tree, $index, $info->{subclass
}, $path);
77 # check if method is unique
79 $realpath =~ s/\{[^\}]+\}/\{\}/g;
80 my $fullpath = "$info->{method} $realpath";
81 die "duplicate path '$realpath'" if $index->{$fullpath};
82 $index->{$fullpath} = $info;
88 foreach my $dir (split('/', $path)) {
91 $res = (grep { $_->{text
} eq $dir } @$treedir)[0];
93 $res->{children
} = [] if !$res->{children
};
94 $treedir = $res->{children
};
101 push @$treedir, $res;
102 $treedir = $res->{children
};
108 foreach my $k (keys %$info) {
109 next if $k eq 'code' || $k eq "match_name" || $k eq "match_re" ||
114 if ($k eq 'parameters') {
115 $data->{$k} = api_clone_schema
($d);
118 $data->{$k} = ref($d) ? clone
($d) : $d;
121 $res->{info
}->{$info->{method}} = $data;
127 sub api_dump_cleanup_tree
{
130 foreach my $rec (@$tree) {
131 delete $rec->{children
} if $rec->{children
} && !scalar(@{$rec->{children
}});
132 if ($rec->{children
}) {
134 api_dump_cleanup_tree
($rec->{children
});
142 # api_dump_remove_refs: prepare API tree for use with to_json($tree)
143 sub api_dump_remove_refs
{
146 my $class = ref($tree);
147 return $tree if !$class;
149 if ($class eq 'ARRAY') {
151 foreach my $el (@$tree) {
152 push @$res, api_dump_remove_refs
($el);
155 } elsif ($class eq 'HASH') {
157 foreach my $k (keys %$tree) {
158 if (my $itemclass = ref($tree->{$k})) {
159 if ($itemclass eq 'CODE') {
160 next if $k eq 'completion';
162 $res->{$k} = api_dump_remove_refs
($tree->{$k});
164 $res->{$k} = $tree->{$k};
168 } elsif ($class eq 'Regexp') {
169 return "$tree"; # return string representation
171 die "unknown class '$class'\n";
176 my ($class, $prefix) = @_;
181 api_dump_full
($tree, $index, $class);
182 api_dump_cleanup_tree
($tree);
186 sub validate_method_schemas
{
188 foreach my $class (keys %$method_registry) {
189 my $ma = $method_registry->{$class};
191 foreach my $info (@$ma) {
192 PVE
::JSONSchema
::validate_method_info
($info);
197 sub register_method
{
198 my ($self, $info) = @_;
206 if ($info->{subclass
}) {
207 $errprefix = "register subclass $info->{subclass} at ${self}/$info->{path} -";
208 $method = 'SUBCLASS';
210 $errprefix = "register method ${self}/$info->{path} -";
211 $info->{method} = 'GET' if !$info->{method};
212 $method = $info->{method};
215 $method_path_lookup->{$self} = {} if !defined($method_path_lookup->{$self});
216 my $path_lookup = $method_path_lookup->{$self};
218 die "$errprefix no path" if !defined($info->{path
});
220 foreach my $comp (split(/\/+/, $info->{path
})) {
221 die "$errprefix path compoment has zero length\n" if $comp eq '';
223 if ($comp =~ m/^\{(\w+)(:(.*))?\}$/) {
225 $regex = $3 ?
$3 : '\S+';
226 push @$match_re, $regex;
227 push @$match_name, $name;
230 push @$match_re, $name;
231 push @$match_name, undef;
235 $path_lookup->{regex
} = {} if !defined($path_lookup->{regex
});
237 my $old_name = $path_lookup->{regex
}->{match_name
};
238 die "$errprefix found changed regex match name\n"
239 if defined($old_name) && ($old_name ne $name);
240 my $old_re = $path_lookup->{regex
}->{match_re
};
241 die "$errprefix found changed regex\n"
242 if defined($old_re) && ($old_re ne $regex);
243 $path_lookup->{regex
}->{match_name
} = $name;
244 $path_lookup->{regex
}->{match_re
} = $regex;
246 die "$errprefix path match error - regex and fixed items\n"
247 if defined($path_lookup->{folders
});
249 $path_lookup = $path_lookup->{regex
};
252 $path_lookup->{folders
}->{$name} = {} if !defined($path_lookup->{folders
}->{$name});
254 die "$errprefix path match error - regex and fixed items\n"
255 if defined($path_lookup->{regex
});
257 $path_lookup = $path_lookup->{folders
}->{$name};
261 die "$errprefix duplicate method definition\n"
262 if defined($path_lookup->{$method});
264 if ($method eq 'SUBCLASS') {
265 foreach my $m (qw(GET PUT POST DELETE)) {
266 die "$errprefix duplicate method definition SUBCLASS and $m\n" if $path_lookup->{$m};
269 $path_lookup->{$method} = $info;
271 $info->{match_re
} = $match_re;
272 $info->{match_name
} = $match_name;
274 $method_by_name->{$self} = {} if !defined($method_by_name->{$self});
277 die "$errprefix method name already defined\n"
278 if defined($method_by_name->{$self}->{$info->{name
}});
280 $method_by_name->{$self}->{$info->{name
}} = $info;
283 push @{$method_registry->{$self}}, $info;
286 sub DESTROY
{}; # avoid problems with autoload
291 # also see "man perldiag"
294 (my $method = $sub) =~ s/.*:://;
296 my $info = $this->map_method_by_name($method);
300 return $self->handle($info, @_);
305 sub method_attributes
{
308 return $method_registry->{$self};
311 sub map_method_by_name
{
312 my ($self, $name) = @_;
314 my $info = $method_by_name->{$self}->{$name};
315 die "no such method '${self}::$name'\n" if !$info;
320 sub map_path_to_methods
{
321 my ($class, $stack, $uri_param, $pathmatchref) = @_;
323 my $path_lookup = $method_path_lookup->{$class};
325 # Note: $pathmatchref can be used to obtain path including
326 # uri patterns like '/cluster/firewall/groups/{group}'.
327 # Used by pvesh to display help
328 if (defined($pathmatchref)) {
329 $$pathmatchref = '' if !$$pathmatchref;
332 while (defined(my $comp = shift @$stack)) {
333 return undef if !$path_lookup; # not registerd?
334 if ($path_lookup->{regex
}) {
335 my $name = $path_lookup->{regex
}->{match_name
};
336 my $regex = $path_lookup->{regex
}->{match_re
};
338 return undef if $comp !~ m/^($regex)$/;
339 $uri_param->{$name} = $1;
340 $path_lookup = $path_lookup->{regex
};
341 $$pathmatchref .= '/{' . $name . '}' if defined($pathmatchref);
342 } elsif ($path_lookup->{folders
}) {
343 $path_lookup = $path_lookup->{folders
}->{$comp};
344 $$pathmatchref .= '/' . $comp if defined($pathmatchref);
346 die "internal error";
349 return undef if !$path_lookup;
351 if (my $info = $path_lookup->{SUBCLASS
}) {
352 $class = $info->{subclass
};
354 my $fd = $info->{fragmentDelimiter
};
357 # we only support the empty string '' (match whole URI)
358 die "unsupported fragmentDelimiter '$fd'"
361 $stack = [ join ('/', @$stack) ] if scalar(@$stack) > 1;
363 $path_lookup = $method_path_lookup->{$class};
367 return undef if !$path_lookup;
369 return ($class, $path_lookup);
373 my ($class, $method, $path, $uri_param, $pathmatchref) = @_;
375 my $stack = [ grep { length($_) > 0 } split('\/+' , $path)]; # skip empty fragments
377 my ($handler_class, $path_info);
379 ($handler_class, $path_info) = $class->map_path_to_methods($stack, $uri_param, $pathmatchref);
382 syslog
('err', $err) if $err;
384 return undef if !($handler_class && $path_info);
386 my $method_info = $path_info->{$method};
388 return undef if !$method_info;
390 return ($handler_class, $method_info);
394 my ($self, $info, $param) = @_;
396 my $func = $info->{code
};
398 if (!($info->{name
} && $func)) {
399 raise
("Method lookup failed ('$info->{name}')\n",
400 code
=> HTTP_INTERNAL_SERVER_ERROR
);
403 if (my $schema = $info->{parameters
}) {
404 # warn "validate ". Dumper($param}) . "\n" . Dumper($schema);
405 PVE
::JSONSchema
::validate
($param, $schema);
406 # untaint data (already validated)
407 my $extra = delete $param->{'extra-args'};
408 while (my ($key, $val) = each %$param) {
409 ($param->{$key}) = $val =~ /^(.*)$/s;
411 $param->{'extra-args'} = [map { /^(.*)$/ } @$extra] if $extra;
414 my $result = &$func($param);
416 # todo: this is only to be safe - disable?
417 if (my $schema = $info->{returns
}) {
418 PVE
::JSONSchema
::validate
($result, $schema, "Result verification failed\n");
424 # format option, display type and description
426 # $display_name: for example "-$name" of "<$name>", pass undef to use "$name:"
427 # $phash: json schema property hash
428 # $format: 'asciidoc', 'short', 'long' or 'full'
429 # $style: 'config', 'config-sub', 'arg' or 'fixed'
430 # $mapdef: parameter mapping ({ desc => XXX, func => sub {...} })
431 my $get_property_description = sub {
432 my ($name, $style, $phash, $format, $hidepw, $mapdef) = @_;
436 $format = 'asciidoc' if !defined($format);
438 my $descr = $phash->{description
} || "no description available";
440 if ($phash->{verbose_description
} &&
441 ($style eq 'config' || $style eq 'config-sub')) {
442 $descr = $phash->{verbose_description
};
447 my $type_text = PVE
::JSONSchema
::schema_get_type_text
($phash, $style);
449 if ($hidepw && $name eq 'password') {
453 if ($mapdef && $phash->{type
} eq 'string') {
454 $type_text = $mapdef->{desc
};
457 if ($format eq 'asciidoc') {
459 if ($style eq 'config') {
461 } elsif ($style eq 'config-sub') {
463 } elsif ($style eq 'arg') {
464 $res .= "`--$name` ";
465 } elsif ($style eq 'fixed') {
466 $res .= "`<$name>`: ";
468 die "unknown style '$style'";
471 $res .= "`$type_text` " if $type_text;
473 if (defined(my $dv = $phash->{default})) {
474 $res .= "('default =' `$dv`)";
477 if ($style eq 'config-sub') {
485 $wdescr =~ s/^$/+/mg;
487 $res .= $wdescr . "\n";
489 if (my $req = $phash->{requires
}) {
490 my $tmp .= ref($req) ?
join(', ', @$req) : $req;
491 $res .= "+\nNOTE: Requires option(s): `$tmp`\n";
495 } elsif ($format eq 'short' || $format eq 'long' || $format eq 'full') {
498 if (defined(my $dv = $phash->{default})) {
499 $defaulttxt = " (default=$dv)";
503 if ($style eq 'config') {
504 $display_name = "$name:";
505 } elsif ($style eq 'arg') {
506 $display_name = "-$name";
507 } elsif ($style eq 'fixed') {
508 $display_name = "<$name>";
510 die "unknown style '$style'";
513 my $tmp = sprintf " %-10s %s$defaulttxt\n", $display_name, "$type_text";
516 $res .= Text
::Wrap
::wrap
('', $indend, ($tmp));
518 $res .= Text
::Wrap
::wrap
($indend, $indend, ($descr)) . "\n\n";
520 if (my $req = $phash->{requires
}) {
521 my $tmp = "Requires option(s): ";
522 $tmp .= ref($req) ?
join(', ', @$req) : $req;
523 $res .= Text
::Wrap
::wrap
($indend, $indend, ($tmp)). "\n\n";
527 die "unknown format '$format'";
533 # translate parameter mapping definition
534 # $mapping_array is a array which can contain:
535 # strings ... in that case we assume it is a parameter name, and
536 # we want to load that parameter from a file
537 # [ param_name, func, desc] ... allows you to specify a arbitrary
538 # mapping func for any param
540 # Returns: a hash indexed by parameter_name,
541 # i.e. { param_name => { func => .., desc => ... } }
542 my $compute_param_mapping_hash = sub {
543 my ($mapping_array) = @_;
547 return $res if !defined($mapping_array);
549 foreach my $item (@$mapping_array) {
550 my ($name, $func, $desc, $interactive);
551 if (ref($item) eq 'ARRAY') {
552 ($name, $func, $desc, $interactive) = @$item;
555 $func = sub { return PVE
::Tools
::file_get_contents
($_[0]) };
557 $desc //= '<filepath>';
558 $res->{$name} = { desc
=> $desc, func
=> $func, interactive
=> $interactive };
564 # generate usage information for command line tools
566 # $name ... the name of the method
567 # $prefix ... usually something like "$exename $cmd" ('pvesm add')
568 # $arg_param ... list of parameters we want to get as ordered arguments
569 # on the command line (or single parameter name for lists)
570 # $fixed_param ... do not generate and info about those parameters
572 # 'long' ... default (text, list all options)
573 # 'short' ... command line only (text, one line)
574 # 'full' ... text, include description
575 # 'asciidoc' ... generate asciidoc for man pages (like 'full')
576 # $hidepw ... hide password option (use this if you provide a read passwork callback)
577 # $param_mapping_func ... mapping for string parameters to file path parameters
579 my ($self, $name, $prefix, $arg_param, $fixed_param, $format, $hidepw, $param_mapping_func) = @_;
581 $format = 'long' if !$format;
583 my $info = $self->map_method_by_name($name);
584 my $schema = $info->{parameters
};
585 my $prop = $schema->{properties
};
593 $arg_param = [ $arg_param ] if $arg_param && !ref($arg_param);
595 foreach my $p (@$arg_param) {
596 next if !$prop->{$p}; # just to be sure
597 my $pd = $prop->{$p};
600 $args .= " " if $args;
601 if ($pd->{format
} && $pd->{format
} =~ m/-list/) {
604 $args .= $pd->{optional
} ?
"[<$p>]" : "<$p>";
609 foreach my $k (@$arg_param) {
610 next if defined($fixed_param->{$k}); # just to be sure
611 next if !$prop->{$k}; # just to be sure
612 $argdescr .= &$get_property_description($k, 'fixed', $prop->{$k}, $format, 0);
615 my $idx_param = {}; # -vlan\d+ -scsi\d+
618 foreach my $k (sort keys %$prop) {
619 next if $arg_hash->{$k};
620 next if defined($fixed_param->{$k});
622 my $type_text = $prop->{$k}->{type
} || 'string';
624 next if $hidepw && ($k eq 'password') && !$prop->{$k}->{optional
};
627 if ($k =~ m/^([a-z]+)(\d+)$/) {
628 my ($name, $idx) = ($1, $2);
629 next if $idx_param->{$name};
630 if ($idx == 0 && defined($prop->{"${name}1"})) {
631 $idx_param->{$name} = 1;
632 $base = "${name}[n]";
636 my $param_mapping_hash = $compute_param_mapping_hash->(&$param_mapping_func($name))
637 if $param_mapping_func;
639 $opts .= &$get_property_description($base, 'arg', $prop->{$k}, $format,
640 $hidepw, $param_mapping_hash->{$k});
642 if (!$prop->{$k}->{optional
}) {
643 $args .= " " if $args;
644 $args .= "--$base <$type_text>"
648 if ($format eq 'asciidoc') {
649 $out .= "*${prefix}*";
650 $out .= " `$args`" if $args;
651 $out .= $opts ?
" `[OPTIONS]`\n" : "\n";
653 $out .= "USAGE: " if $format ne 'short';
654 $out .= "$prefix $args";
655 $out .= $opts ?
" [OPTIONS]\n" : "\n";
658 return $out if $format eq 'short';
660 if ($info->{description
}) {
661 if ($format eq 'asciidoc') {
662 my $desc = Text
::Wrap
::wrap
('', '', ($info->{description
}));
663 $out .= "\n$desc\n\n";
664 } elsif ($format eq 'full') {
665 my $desc = Text
::Wrap
::wrap
(' ', ' ', ($info->{description
}));
666 $out .= "\n$desc\n\n";
670 $out .= $argdescr if $argdescr;
672 $out .= $opts if $opts;
677 # generate docs from JSON schema properties
678 sub dump_properties
{
679 my ($prop, $format, $style, $filterFn) = @_;
685 my $idx_param = {}; # -vlan\d+ -scsi\d+
687 foreach my $k (sort keys %$prop) {
688 my $phash = $prop->{$k};
690 next if defined($filterFn) && &$filterFn($k, $phash);
691 next if $phash->{alias
};
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]";
703 $raw .= &$get_property_description($base, $style, $phash, $format, 0);
705 next if $style ne 'config';
707 my $prop_fmt = $phash->{format
};
710 if (ref($prop_fmt) ne 'HASH') {
711 $prop_fmt = PVE
::JSONSchema
::get_format
($prop_fmt);
714 next if !(ref($prop_fmt) && (ref($prop_fmt) eq 'HASH'));
716 $raw .= dump_properties
($prop_fmt, $format, 'config-sub')
723 my $replace_file_names_with_contents = sub {
724 my ($param, $param_mapping_hash) = @_;
726 while (my ($k, $d) = each %$param_mapping_hash) {
727 next if $d->{interactive
}; # handled by the JSONSchema's get_options code
728 $param->{$k} = $d->{func
}->($param->{$k})
729 if defined($param->{$k});
736 my ($self, $prefix, $name, $args, $arg_param, $fixed_param, $read_password_func, $param_mapping_func) = @_;
738 my $info = $self->map_method_by_name($name);
742 my $param_mapping_hash = $compute_param_mapping_hash->($param_mapping_func->($name)) if $param_mapping_func;
743 my $param = PVE
::JSONSchema
::get_options
($info->{parameters
}, $args, $arg_param, $fixed_param, $read_password_func, $param_mapping_hash);
745 if (defined($param_mapping_hash)) {
746 &$replace_file_names_with_contents($param, $param_mapping_hash);
749 $res = $self->handle($info, $param);
754 die $err if !$ec || $ec ne "PVE::Exception" || !$err->is_param_exc();
756 $err->{usage
} = $self->usage_str($name, $prefix, $arg_param, $fixed_param, 'short', $read_password_func, $param_mapping_func);
765 # note: this modifies the original hash by adding the id property
767 my ($hash, $idprop) = @_;
770 return $res if !$hash;
772 foreach my $k (keys %$hash) {
773 $hash->{$k}->{$idprop} = $k;
774 push @$res, $hash->{$k};