1 package PVE
::APIClient
::RESTHandler
;
4 no strict
'refs'; # our autoload requires this
6 use PVE
::APIClient
::SafeSyslog
;
7 use PVE
::APIClient
::Exception
qw(raise raise_param_exc);
8 use PVE
::APIClient
::JSONSchema
;
9 use PVE
::APIClient
::Tools
;
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
::APIClient
::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, $raw_dump) = @_;
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, $raw_dump);
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" ||
117 if ($k eq 'parameters') {
118 $data->{$k} = api_clone_schema
($d);
120 $data->{$k} = ref($d) ? clone
($d) : $d;
124 $res->{info
}->{$info->{method}} = $data;
130 sub api_dump_cleanup_tree
{
133 foreach my $rec (@$tree) {
134 delete $rec->{children
} if $rec->{children
} && !scalar(@{$rec->{children
}});
135 if ($rec->{children
}) {
137 api_dump_cleanup_tree
($rec->{children
});
145 # api_dump_remove_refs: prepare API tree for use with to_json($tree)
146 sub api_dump_remove_refs
{
149 my $class = ref($tree);
150 return $tree if !$class;
152 if ($class eq 'ARRAY') {
154 foreach my $el (@$tree) {
155 push @$res, api_dump_remove_refs
($el);
158 } elsif ($class eq 'HASH') {
160 foreach my $k (keys %$tree) {
161 if (my $itemclass = ref($tree->{$k})) {
162 if ($itemclass eq 'CODE') {
163 next if $k eq 'completion';
165 $res->{$k} = api_dump_remove_refs
($tree->{$k});
167 $res->{$k} = $tree->{$k};
171 } elsif ($class eq 'Regexp') {
172 return "$tree"; # return string representation
174 die "unknown class '$class'\n";
179 my ($class, $prefix, $raw_dump) = @_;
184 api_dump_full
($tree, $index, $class, $prefix, $raw_dump);
185 api_dump_cleanup_tree
($tree);
189 sub validate_method_schemas
{
191 foreach my $class (keys %$method_registry) {
192 my $ma = $method_registry->{$class};
194 foreach my $info (@$ma) {
195 PVE
::APIClient
::JSONSchema
::validate_method_info
($info);
200 sub register_method
{
201 my ($self, $info) = @_;
209 if ($info->{subclass
}) {
210 $errprefix = "register subclass $info->{subclass} at ${self}/$info->{path} -";
211 $method = 'SUBCLASS';
213 $errprefix = "register method ${self}/$info->{path} -";
214 $info->{method} = 'GET' if !$info->{method};
215 $method = $info->{method};
218 $method_path_lookup->{$self} = {} if !defined($method_path_lookup->{$self});
219 my $path_lookup = $method_path_lookup->{$self};
221 die "$errprefix no path" if !defined($info->{path
});
223 foreach my $comp (split(/\/+/, $info->{path
})) {
224 die "$errprefix path compoment has zero length\n" if $comp eq '';
226 if ($comp =~ m/^\{(\w+)(:(.*))?\}$/) {
228 $regex = $3 ?
$3 : '\S+';
229 push @$match_re, $regex;
230 push @$match_name, $name;
233 push @$match_re, $name;
234 push @$match_name, undef;
238 $path_lookup->{regex
} = {} if !defined($path_lookup->{regex
});
240 my $old_name = $path_lookup->{regex
}->{match_name
};
241 die "$errprefix found changed regex match name\n"
242 if defined($old_name) && ($old_name ne $name);
243 my $old_re = $path_lookup->{regex
}->{match_re
};
244 die "$errprefix found changed regex\n"
245 if defined($old_re) && ($old_re ne $regex);
246 $path_lookup->{regex
}->{match_name
} = $name;
247 $path_lookup->{regex
}->{match_re
} = $regex;
249 die "$errprefix path match error - regex and fixed items\n"
250 if defined($path_lookup->{folders
});
252 $path_lookup = $path_lookup->{regex
};
255 $path_lookup->{folders
}->{$name} = {} if !defined($path_lookup->{folders
}->{$name});
257 die "$errprefix path match error - regex and fixed items\n"
258 if defined($path_lookup->{regex
});
260 $path_lookup = $path_lookup->{folders
}->{$name};
264 die "$errprefix duplicate method definition\n"
265 if defined($path_lookup->{$method});
267 if ($method eq 'SUBCLASS') {
268 foreach my $m (qw(GET PUT POST DELETE)) {
269 die "$errprefix duplicate method definition SUBCLASS and $m\n" if $path_lookup->{$m};
272 $path_lookup->{$method} = $info;
274 $info->{match_re
} = $match_re;
275 $info->{match_name
} = $match_name;
277 $method_by_name->{$self} = {} if !defined($method_by_name->{$self});
280 die "$errprefix method name already defined\n"
281 if defined($method_by_name->{$self}->{$info->{name
}});
283 $method_by_name->{$self}->{$info->{name
}} = $info;
286 push @{$method_registry->{$self}}, $info;
289 sub DESTROY
{}; # avoid problems with autoload
294 # also see "man perldiag"
297 (my $method = $sub) =~ s/.*:://;
299 my $info = $this->map_method_by_name($method);
303 return $self->handle($info, @_);
308 sub method_attributes
{
311 return $method_registry->{$self};
314 sub map_method_by_name
{
315 my ($self, $name) = @_;
317 my $info = $method_by_name->{$self}->{$name};
318 die "no such method '${self}::$name'\n" if !$info;
323 sub map_path_to_methods
{
324 my ($class, $stack, $uri_param, $pathmatchref) = @_;
326 my $path_lookup = $method_path_lookup->{$class};
328 # Note: $pathmatchref can be used to obtain path including
329 # uri patterns like '/cluster/firewall/groups/{group}'.
330 # Used by pvesh to display help
331 if (defined($pathmatchref)) {
332 $$pathmatchref = '' if !$$pathmatchref;
335 while (defined(my $comp = shift @$stack)) {
336 return undef if !$path_lookup; # not registerd?
337 if ($path_lookup->{regex
}) {
338 my $name = $path_lookup->{regex
}->{match_name
};
339 my $regex = $path_lookup->{regex
}->{match_re
};
341 return undef if $comp !~ m/^($regex)$/;
342 $uri_param->{$name} = $1;
343 $path_lookup = $path_lookup->{regex
};
344 $$pathmatchref .= '/{' . $name . '}' if defined($pathmatchref);
345 } elsif ($path_lookup->{folders
}) {
346 $path_lookup = $path_lookup->{folders
}->{$comp};
347 $$pathmatchref .= '/' . $comp if defined($pathmatchref);
349 die "internal error";
352 return undef if !$path_lookup;
354 if (my $info = $path_lookup->{SUBCLASS
}) {
355 $class = $info->{subclass
};
357 my $fd = $info->{fragmentDelimiter
};
360 # we only support the empty string '' (match whole URI)
361 die "unsupported fragmentDelimiter '$fd'"
364 $stack = [ join ('/', @$stack) ] if scalar(@$stack) > 1;
366 $path_lookup = $method_path_lookup->{$class};
370 return undef if !$path_lookup;
372 return ($class, $path_lookup);
376 my ($class, $method, $path, $uri_param, $pathmatchref) = @_;
378 my $stack = [ grep { length($_) > 0 } split('\/+' , $path)]; # skip empty fragments
380 my ($handler_class, $path_info);
382 ($handler_class, $path_info) = $class->map_path_to_methods($stack, $uri_param, $pathmatchref);
385 syslog
('err', $err) if $err;
387 return undef if !($handler_class && $path_info);
389 my $method_info = $path_info->{$method};
391 return undef if !$method_info;
393 return ($handler_class, $method_info);
397 my ($self, $info, $param, $output_options) = @_;
399 my $func = $info->{code
};
401 if (!($info->{name
} && $func)) {
402 raise
("Method lookup failed ('$info->{name}')\n",
403 code
=> HTTP_INTERNAL_SERVER_ERROR
);
406 if (my $schema = $info->{parameters
}) {
407 # warn "validate ". Dumper($param}) . "\n" . Dumper($schema);
408 PVE
::APIClient
::JSONSchema
::validate
($param, $schema);
409 # untaint data (already validated)
410 my $extra = delete $param->{'extra-args'};
411 while (my ($key, $val) = each %$param) {
412 ($param->{$key}) = $val =~ /^(.*)$/s;
414 $param->{'extra-args'} = [map { /^(.*)$/ } @$extra] if $extra;
417 $output_options //= {};
418 my $result = &$func($param, $output_options);
420 # todo: this is only to be safe - disable?
421 if (my $schema = $info->{returns
}) {
422 PVE
::APIClient
::JSONSchema
::validate
($result, $schema, "Result verification failed\n");
428 # format option, display type and description
430 # $display_name: for example "-$name" of "<$name>", pass undef to use "$name:"
431 # $phash: json schema property hash
432 # $format: 'asciidoc', 'short', 'long' or 'full'
433 # $style: 'config', 'config-sub', 'arg' or 'fixed'
434 # $mapdef: parameter mapping ({ desc => XXX, func => sub {...} })
435 my $get_property_description = sub {
436 my ($name, $style, $phash, $format, $mapdef) = @_;
440 $format = 'asciidoc' if !defined($format);
442 my $descr = $phash->{description
} || "no description available";
444 if ($phash->{verbose_description
} &&
445 ($style eq 'config' || $style eq 'config-sub')) {
446 $descr = $phash->{verbose_description
};
451 my $type_text = PVE
::APIClient
::JSONSchema
::schema_get_type_text
($phash, $style);
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;
553 } elsif (ref($item) eq 'HASH') {
555 $res->{$item->{name
}} = $item;
559 $func = sub { return PVE
::APIClient
::Tools
::file_get_contents
($_[0]) };
561 $desc //= '<filepath>';
562 $res->{$name} = { desc
=> $desc, func
=> $func, interactive
=> $interactive };
568 # generate usage information for command line tools
570 # $info ... method info
571 # $prefix ... usually something like "$exename $cmd" ('pvesm add')
572 # $arg_param ... list of parameters we want to get as ordered arguments
573 # on the command line (or single parameter name for lists)
574 # $fixed_param ... do not generate and info about those parameters
576 # 'long' ... default (text, list all options)
577 # 'short' ... command line only (text, one line)
578 # 'full' ... text, include description
579 # 'asciidoc' ... generate asciidoc for man pages (like 'full')
580 # $param_cb ... mapping for string parameters to file path parameters
582 my ($info, $prefix, $arg_param, $fixed_param, $format, $param_cb) = @_;
584 $format = 'long' if !$format;
586 my $schema = $info->{parameters
};
587 my $name = $info->{name
};
588 my $prop = $schema->{properties
};
596 $arg_param = [ $arg_param ] if $arg_param && !ref($arg_param);
598 foreach my $p (@$arg_param) {
599 next if !$prop->{$p}; # just to be sure
600 my $pd = $prop->{$p};
603 $args .= " " if $args;
604 if ($pd->{format
} && $pd->{format
} =~ m/-list/) {
607 $args .= $pd->{optional
} ?
"[<$p>]" : "<$p>";
612 foreach my $k (@$arg_param) {
613 next if defined($fixed_param->{$k}); # just to be sure
614 next if !$prop->{$k}; # just to be sure
615 $argdescr .= $get_property_description->($k, 'fixed', $prop->{$k}, $format);
618 my $idx_param = {}; # -vlan\d+ -scsi\d+
621 foreach my $k (sort keys %$prop) {
622 next if $arg_hash->{$k};
623 next if defined($fixed_param->{$k});
625 my $type_text = $prop->{$k}->{type
} || 'string';
629 if (defined($param_cb)) {
630 my $mapping = $param_cb->($name);
631 $param_map = $compute_param_mapping_hash->($mapping);
632 next if $k eq 'password' && $param_map->{$k} && !$prop->{$k}->{optional
};
636 if ($k =~ m/^([a-z]+)(\d+)$/) {
637 my ($name, $idx) = ($1, $2);
638 next if $idx_param->{$name};
639 if ($idx == 0 && defined($prop->{"${name}1"})) {
640 $idx_param->{$name} = 1;
641 $base = "${name}[n]";
646 $opts .= $get_property_description->($base, 'arg', $prop->{$k}, $format, $param_map->{$k});
648 if (!$prop->{$k}->{optional
}) {
649 $args .= " " if $args;
650 $args .= "--$base <$type_text>"
654 if ($format eq 'asciidoc') {
655 $out .= "*${prefix}*";
656 $out .= " `$args`" if $args;
657 $out .= $opts ?
" `[OPTIONS]`\n" : "\n";
659 $out .= "USAGE: " if $format ne 'short';
660 $out .= "$prefix $args";
661 $out .= $opts ?
" [OPTIONS]\n" : "\n";
664 return $out if $format eq 'short';
666 if ($info->{description
}) {
667 if ($format eq 'asciidoc') {
668 my $desc = Text
::Wrap
::wrap
('', '', ($info->{description
}));
669 $out .= "\n$desc\n\n";
670 } elsif ($format eq 'full') {
671 my $desc = Text
::Wrap
::wrap
(' ', ' ', ($info->{description
}));
672 $out .= "\n$desc\n\n";
676 $out .= $argdescr if $argdescr;
678 $out .= $opts if $opts;
684 my ($self, $name, $prefix, $arg_param, $fixed_param, $format, $param_cb) = @_;
686 my $info = $self->map_method_by_name($name);
688 return getopt_usage
($info, $prefix, $arg_param, $fixed_param, $format, $param_cb);
691 # generate docs from JSON schema properties
692 sub dump_properties
{
693 my ($prop, $format, $style, $filterFn) = @_;
699 my $idx_param = {}; # -vlan\d+ -scsi\d+
701 foreach my $k (sort keys %$prop) {
702 my $phash = $prop->{$k};
704 next if defined($filterFn) && &$filterFn($k, $phash);
705 next if $phash->{alias
};
708 if ($k =~ m/^([a-z]+)(\d+)$/) {
709 my ($name, $idx) = ($1, $2);
710 next if $idx_param->{$name};
711 if ($idx == 0 && defined($prop->{"${name}1"})) {
712 $idx_param->{$name} = 1;
713 $base = "${name}[n]";
717 $raw .= $get_property_description->($base, $style, $phash, $format);
719 next if $style ne 'config';
721 my $prop_fmt = $phash->{format
};
724 if (ref($prop_fmt) ne 'HASH') {
725 $prop_fmt = PVE
::APIClient
::JSONSchema
::get_format
($prop_fmt);
728 next if !(ref($prop_fmt) && (ref($prop_fmt) eq 'HASH'));
730 $raw .= dump_properties
($prop_fmt, $format, 'config-sub')
737 my $replace_file_names_with_contents = sub {
738 my ($param, $param_map) = @_;
740 while (my ($k, $d) = each %$param_map) {
741 next if $d->{interactive
}; # handled by the JSONSchema's get_options code
742 $param->{$k} = $d->{func
}->($param->{$k})
743 if defined($param->{$k});
749 our $standard_output_options = {
750 format
=> PVE
::APIClient
::JSONSchema
::get_standard_option
('pve-output-format'),
752 description
=> "Do not show column headers (for 'text' format).",
758 description
=> "Do not draw borders (for 'text' format).",
764 description
=> "Suppress printing results.",
768 'human-readable' => {
769 description
=> "Call output rendering functions to produce human readable text.",
776 sub add_standard_output_parameters
{
777 my ($org_schema) = @_;
779 my $schema = { %$org_schema };
780 $schema->{properties
} = { %{$schema->{properties
}}, %$standard_output_options };
786 my ($self, $prefix, $name, $args, $arg_param, $fixed_param, $param_cb, $options) = @_;
788 my $info = $self->map_method_by_name($name);
794 $param_map = $compute_param_mapping_hash->($param_cb->($name)) if $param_cb;
795 my $schema = add_standard_output_parameters
($info->{parameters
});
796 my $param = PVE
::APIClient
::JSONSchema
::get_options
($schema, $args, $arg_param, $fixed_param, $param_map);
798 foreach my $opt (keys %$standard_output_options) {
799 $options->{$opt} = delete $param->{$opt} if defined($param->{$opt});
802 if (defined($param_map)) {
803 $replace_file_names_with_contents->($param, $param_map);
806 $res = $self->handle($info, $param, $options);
811 die $err if !$ec || $ec ne "PVE::APIClient::Exception" || !$err->is_param_exc();
813 $err->{usage
} = $self->usage_str($name, $prefix, $arg_param, $fixed_param, 'short', $param_cb);
822 # note: this modifies the original hash by adding the id property
824 my ($hash, $idprop) = @_;
827 return $res if !$hash;
829 foreach my $k (keys %$hash) {
830 $hash->{$k}->{$idprop} = $k;
831 push @$res, $hash->{$k};