introduce compute_param_mapping_hash helper
[pve-common.git] / src / PVE / RESTHandler.pm
1 package PVE::RESTHandler;
2
3 use strict;
4 no strict 'refs'; # our autoload requires this
5 use warnings;
6 use PVE::SafeSyslog;
7 use PVE::Exception qw(raise raise_param_exc);
8 use PVE::JSONSchema;
9 use PVE::Tools;
10 use HTTP::Status qw(:constants :is status_message);
11 use Text::Wrap;
12 use Clone qw(clone);
13
14 my $method_registry = {};
15 my $method_by_name = {};
16 my $method_path_lookup = {};
17
18 our $AUTOLOAD; # it's a package global
19
20 sub api_clone_schema {
21 my ($schema) = @_;
22
23 my $res = {};
24 my $ref = ref($schema);
25 die "not a HASH reference" if !($ref && $ref eq 'HASH');
26
27 foreach my $k (keys %$schema) {
28 my $d = $schema->{$k};
29 if ($k ne 'properties') {
30 $res->{$k} = ref($d) ? clone($d) : $d;
31 next;
32 }
33 # convert indexed parameters like -net\d+ to -net[n]
34 foreach my $p (keys %$d) {
35 my $pd = $d->{$p};
36 if ($p =~ m/^([a-z]+)(\d+)$/) {
37 my ($name, $idx) = ($1, $2);
38 if ($idx == 0 && defined($d->{"${name}1"})) {
39 $p = "${name}[n]";
40 } elsif (defined($d->{"${name}0"})) {
41 next; # only handle once for -xx0, but only if -xx0 exists
42 }
43 }
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;
51 }
52 }
53 $res->{$k}->{$p} = $tmp;
54 }
55 }
56
57 return $res;
58 }
59
60 sub api_dump_full {
61 my ($tree, $index, $class, $prefix) = @_;
62
63 $prefix = '' if !$prefix;
64
65 my $ma = $method_registry->{$class};
66
67 foreach my $info (@$ma) {
68
69 my $path = "$prefix/$info->{path}";
70 $path =~ s/\/+$//;
71
72 if ($info->{subclass}) {
73 api_dump_full($tree, $index, $info->{subclass}, $path);
74 } else {
75 next if !$path;
76
77 # check if method is unique
78 my $realpath = $path;
79 $realpath =~ s/\{[^\}]+\}/\{\}/g;
80 my $fullpath = "$info->{method} $realpath";
81 die "duplicate path '$realpath'" if $index->{$fullpath};
82 $index->{$fullpath} = $info;
83
84 # insert into tree
85 my $treedir = $tree;
86 my $res;
87 my $sp = '';
88 foreach my $dir (split('/', $path)) {
89 next if !$dir;
90 $sp .= "/$dir";
91 $res = (grep { $_->{text} eq $dir } @$treedir)[0];
92 if ($res) {
93 $res->{children} = [] if !$res->{children};
94 $treedir = $res->{children};
95 } else {
96 $res = {
97 path => $sp,
98 text => $dir,
99 children => [],
100 };
101 push @$treedir, $res;
102 $treedir = $res->{children};
103 }
104 }
105
106 if ($res) {
107 my $data = {};
108 foreach my $k (keys %$info) {
109 next if $k eq 'code' || $k eq "match_name" || $k eq "match_re" ||
110 $k eq "path";
111
112 my $d = $info->{$k};
113
114 if ($k eq 'parameters') {
115 $data->{$k} = api_clone_schema($d);
116 } else {
117
118 $data->{$k} = ref($d) ? clone($d) : $d;
119 }
120 }
121 $res->{info}->{$info->{method}} = $data;
122 };
123 }
124 }
125 };
126
127 sub api_dump_cleanup_tree {
128 my ($tree) = @_;
129
130 foreach my $rec (@$tree) {
131 delete $rec->{children} if $rec->{children} && !scalar(@{$rec->{children}});
132 if ($rec->{children}) {
133 $rec->{leaf} = 0;
134 api_dump_cleanup_tree($rec->{children});
135 } else {
136 $rec->{leaf} = 1;
137 }
138 }
139
140 }
141
142 sub api_dump {
143 my ($class, $prefix) = @_;
144
145 my $tree = [];
146
147 my $index = {};
148 api_dump_full($tree, $index, $class);
149 api_dump_cleanup_tree($tree);
150 return $tree;
151 };
152
153 sub validate_method_schemas {
154
155 foreach my $class (keys %$method_registry) {
156 my $ma = $method_registry->{$class};
157
158 foreach my $info (@$ma) {
159 PVE::JSONSchema::validate_method_info($info);
160 }
161 }
162 }
163
164 sub register_method {
165 my ($self, $info) = @_;
166
167 my $match_re = [];
168 my $match_name = [];
169
170 my $errprefix;
171
172 my $method;
173 if ($info->{subclass}) {
174 $errprefix = "register subclass $info->{subclass} at ${self}/$info->{path} -";
175 $method = 'SUBCLASS';
176 } else {
177 $errprefix = "register method ${self}/$info->{path} -";
178 $info->{method} = 'GET' if !$info->{method};
179 $method = $info->{method};
180 }
181
182 $method_path_lookup->{$self} = {} if !defined($method_path_lookup->{$self});
183 my $path_lookup = $method_path_lookup->{$self};
184
185 die "$errprefix no path" if !defined($info->{path});
186
187 foreach my $comp (split(/\/+/, $info->{path})) {
188 die "$errprefix path compoment has zero length\n" if $comp eq '';
189 my ($name, $regex);
190 if ($comp =~ m/^\{(\w+)(:(.*))?\}$/) {
191 $name = $1;
192 $regex = $3 ? $3 : '\S+';
193 push @$match_re, $regex;
194 push @$match_name, $name;
195 } else {
196 $name = $comp;
197 push @$match_re, $name;
198 push @$match_name, undef;
199 }
200
201 if ($regex) {
202 $path_lookup->{regex} = {} if !defined($path_lookup->{regex});
203
204 my $old_name = $path_lookup->{regex}->{match_name};
205 die "$errprefix found changed regex match name\n"
206 if defined($old_name) && ($old_name ne $name);
207 my $old_re = $path_lookup->{regex}->{match_re};
208 die "$errprefix found changed regex\n"
209 if defined($old_re) && ($old_re ne $regex);
210 $path_lookup->{regex}->{match_name} = $name;
211 $path_lookup->{regex}->{match_re} = $regex;
212
213 die "$errprefix path match error - regex and fixed items\n"
214 if defined($path_lookup->{folders});
215
216 $path_lookup = $path_lookup->{regex};
217
218 } else {
219 $path_lookup->{folders}->{$name} = {} if !defined($path_lookup->{folders}->{$name});
220
221 die "$errprefix path match error - regex and fixed items\n"
222 if defined($path_lookup->{regex});
223
224 $path_lookup = $path_lookup->{folders}->{$name};
225 }
226 }
227
228 die "$errprefix duplicate method definition\n"
229 if defined($path_lookup->{$method});
230
231 if ($method eq 'SUBCLASS') {
232 foreach my $m (qw(GET PUT POST DELETE)) {
233 die "$errprefix duplicate method definition SUBCLASS and $m\n" if $path_lookup->{$m};
234 }
235 }
236 $path_lookup->{$method} = $info;
237
238 $info->{match_re} = $match_re;
239 $info->{match_name} = $match_name;
240
241 $method_by_name->{$self} = {} if !defined($method_by_name->{$self});
242
243 if ($info->{name}) {
244 die "$errprefix method name already defined\n"
245 if defined($method_by_name->{$self}->{$info->{name}});
246
247 $method_by_name->{$self}->{$info->{name}} = $info;
248 }
249
250 push @{$method_registry->{$self}}, $info;
251 }
252
253 sub DESTROY {}; # avoid problems with autoload
254
255 sub AUTOLOAD {
256 my ($this) = @_;
257
258 # also see "man perldiag"
259
260 my $sub = $AUTOLOAD;
261 (my $method = $sub) =~ s/.*:://;
262
263 my $info = $this->map_method_by_name($method);
264
265 *{$sub} = sub {
266 my $self = shift;
267 return $self->handle($info, @_);
268 };
269 goto &$AUTOLOAD;
270 }
271
272 sub method_attributes {
273 my ($self) = @_;
274
275 return $method_registry->{$self};
276 }
277
278 sub map_method_by_name {
279 my ($self, $name) = @_;
280
281 my $info = $method_by_name->{$self}->{$name};
282 die "no such method '${self}::$name'\n" if !$info;
283
284 return $info;
285 }
286
287 sub map_path_to_methods {
288 my ($class, $stack, $uri_param, $pathmatchref) = @_;
289
290 my $path_lookup = $method_path_lookup->{$class};
291
292 # Note: $pathmatchref can be used to obtain path including
293 # uri patterns like '/cluster/firewall/groups/{group}'.
294 # Used by pvesh to display help
295 if (defined($pathmatchref)) {
296 $$pathmatchref = '' if !$$pathmatchref;
297 }
298
299 while (defined(my $comp = shift @$stack)) {
300 return undef if !$path_lookup; # not registerd?
301 if ($path_lookup->{regex}) {
302 my $name = $path_lookup->{regex}->{match_name};
303 my $regex = $path_lookup->{regex}->{match_re};
304
305 return undef if $comp !~ m/^($regex)$/;
306 $uri_param->{$name} = $1;
307 $path_lookup = $path_lookup->{regex};
308 $$pathmatchref .= '/{' . $name . '}' if defined($pathmatchref);
309 } elsif ($path_lookup->{folders}) {
310 $path_lookup = $path_lookup->{folders}->{$comp};
311 $$pathmatchref .= '/' . $comp if defined($pathmatchref);
312 } else {
313 die "internal error";
314 }
315
316 return undef if !$path_lookup;
317
318 if (my $info = $path_lookup->{SUBCLASS}) {
319 $class = $info->{subclass};
320
321 my $fd = $info->{fragmentDelimiter};
322
323 if (defined($fd)) {
324 # we only support the empty string '' (match whole URI)
325 die "unsupported fragmentDelimiter '$fd'"
326 if $fd ne '';
327
328 $stack = [ join ('/', @$stack) ] if scalar(@$stack) > 1;
329 }
330 $path_lookup = $method_path_lookup->{$class};
331 }
332 }
333
334 return undef if !$path_lookup;
335
336 return ($class, $path_lookup);
337 }
338
339 sub find_handler {
340 my ($class, $method, $path, $uri_param, $pathmatchref) = @_;
341
342 my $stack = [ grep { length($_) > 0 } split('\/+' , $path)]; # skip empty fragments
343
344 my ($handler_class, $path_info);
345 eval {
346 ($handler_class, $path_info) = $class->map_path_to_methods($stack, $uri_param, $pathmatchref);
347 };
348 my $err = $@;
349 syslog('err', $err) if $err;
350
351 return undef if !($handler_class && $path_info);
352
353 my $method_info = $path_info->{$method};
354
355 return undef if !$method_info;
356
357 return ($handler_class, $method_info);
358 }
359
360 sub handle {
361 my ($self, $info, $param) = @_;
362
363 my $func = $info->{code};
364
365 if (!($info->{name} && $func)) {
366 raise("Method lookup failed ('$info->{name}')\n",
367 code => HTTP_INTERNAL_SERVER_ERROR);
368 }
369
370 if (my $schema = $info->{parameters}) {
371 # warn "validate ". Dumper($param}) . "\n" . Dumper($schema);
372 PVE::JSONSchema::validate($param, $schema);
373 # untaint data (already validated)
374 my $extra = delete $param->{'extra-args'};
375 while (my ($key, $val) = each %$param) {
376 ($param->{$key}) = $val =~ /^(.*)$/s;
377 }
378 $param->{'extra-args'} = [map { /^(.*)$/ } @$extra] if $extra;
379 }
380
381 my $result = &$func($param);
382
383 # todo: this is only to be safe - disable?
384 if (my $schema = $info->{returns}) {
385 PVE::JSONSchema::validate($result, $schema, "Result verification failed\n");
386 }
387
388 return $result;
389 }
390
391 # format option, display type and description
392 # $name: option name
393 # $display_name: for example "-$name" of "<$name>", pass undef to use "$name:"
394 # $phash: json schema property hash
395 # $format: 'asciidoc', 'short', 'long' or 'full'
396 # $style: 'config', 'config-sub', 'arg' or 'fixed'
397 # $mapdef: parameter mapping ({ desc => XXX, func => sub {...} })
398 my $get_property_description = sub {
399 my ($name, $style, $phash, $format, $hidepw, $mapdef) = @_;
400
401 my $res = '';
402
403 $format = 'asciidoc' if !defined($format);
404
405 my $descr = $phash->{description} || "no description available";
406
407 if ($phash->{verbose_description} &&
408 ($style eq 'config' || $style eq 'config-sub')) {
409 $descr = $phash->{verbose_description};
410 }
411
412 chomp $descr;
413
414 my $type_text = PVE::JSONSchema::schema_get_type_text($phash, $style);
415
416 if ($hidepw && $name eq 'password') {
417 $type_text = '';
418 }
419
420 if ($mapdef && $phash->{type} eq 'string') {
421 $type_text = $mapdef->{desc};
422 }
423
424 if ($format eq 'asciidoc') {
425
426 if ($style eq 'config') {
427 $res .= "`$name`: ";
428 } elsif ($style eq 'config-sub') {
429 $res .= "`$name`=";
430 } elsif ($style eq 'arg') {
431 $res .= "`--$name` ";
432 } elsif ($style eq 'fixed') {
433 $res .= "`<$name>`: ";
434 } else {
435 die "unknown style '$style'";
436 }
437
438 $res .= "`$type_text` " if $type_text;
439
440 if (defined(my $dv = $phash->{default})) {
441 $res .= "('default =' `$dv`)";
442 }
443
444 if ($style eq 'config-sub') {
445 $res .= ";;\n\n";
446 } else {
447 $res .= "::\n\n";
448 }
449
450 my $wdescr = $descr;
451 chomp $wdescr;
452 $wdescr =~ s/^$/+/mg;
453
454 $res .= $wdescr . "\n";
455
456 if (my $req = $phash->{requires}) {
457 my $tmp .= ref($req) ? join(', ', @$req) : $req;
458 $res .= "+\nNOTE: Requires option(s): `$tmp`\n";
459 }
460 $res .= "\n";
461
462 } elsif ($format eq 'short' || $format eq 'long' || $format eq 'full') {
463
464 my $defaulttxt = '';
465 if (defined(my $dv = $phash->{default})) {
466 $defaulttxt = " (default=$dv)";
467 }
468
469 my $display_name;
470 if ($style eq 'config') {
471 $display_name = "$name:";
472 } elsif ($style eq 'arg') {
473 $display_name = "-$name";
474 } elsif ($style eq 'fixed') {
475 $display_name = "<$name>";
476 } else {
477 die "unknown style '$style'";
478 }
479
480 my $tmp = sprintf " %-10s %s$defaulttxt\n", $display_name, "$type_text";
481 my $indend = " ";
482
483 $res .= Text::Wrap::wrap('', $indend, ($tmp));
484 $res .= "\n",
485 $res .= Text::Wrap::wrap($indend, $indend, ($descr)) . "\n\n";
486
487 if (my $req = $phash->{requires}) {
488 my $tmp = "Requires option(s): ";
489 $tmp .= ref($req) ? join(', ', @$req) : $req;
490 $res .= Text::Wrap::wrap($indend, $indend, ($tmp)). "\n\n";
491 }
492
493 } else {
494 die "unknown format '$format'";
495 }
496
497 return $res;
498 };
499
500 # translate parameter mapping definition
501 # $mapping_array is a array which can contain:
502 # strings ... in that case we assume it is a parameter name, and
503 # we want to load that parameter from a file
504 # [ param_name, func, desc] ... allows you to specify a arbitrary
505 # mapping func for any param
506 #
507 # Returns: a hash indexed by parameter_name,
508 # i.e. { param_name => { func => .., desc => ... } }
509 my $compute_param_mapping_hash = sub {
510 my ($mapping_array) = @_;
511
512 my $res = {};
513
514 return $res if !defined($mapping_array);
515
516 foreach my $item (@$mapping_array) {
517 my ($name, $func, $desc);
518 if (ref($item) eq 'ARRAY') {
519 ($name, $func, $desc) = @$item;
520 } else {
521 $name = $item;
522 $func = sub { return PVE::Tools::file_get_contents($_[0]) };
523 }
524 $desc //= '<filepath>';
525 $res->{$name} = { desc => $desc, func => $func };
526 }
527
528 return $res;
529 };
530
531 # generate usage information for command line tools
532 #
533 # $name ... the name of the method
534 # $prefix ... usually something like "$exename $cmd" ('pvesm add')
535 # $arg_param ... list of parameters we want to get as ordered arguments
536 # on the command line (or single parameter name for lists)
537 # $fixed_param ... do not generate and info about those parameters
538 # $format:
539 # 'long' ... default (text, list all options)
540 # 'short' ... command line only (text, one line)
541 # 'full' ... text, include description
542 # 'asciidoc' ... generate asciidoc for man pages (like 'full')
543 # $hidepw ... hide password option (use this if you provide a read passwork callback)
544 # $stringfilemap ... mapping for string parameters to file path parameters
545 sub usage_str {
546 my ($self, $name, $prefix, $arg_param, $fixed_param, $format, $hidepw, $stringfilemap) = @_;
547
548 $format = 'long' if !$format;
549
550 my $info = $self->map_method_by_name($name);
551 my $schema = $info->{parameters};
552 my $prop = $schema->{properties};
553
554 my $out = '';
555
556 my $arg_hash = {};
557
558 my $args = '';
559
560 $arg_param = [ $arg_param ] if $arg_param && !ref($arg_param);
561
562 foreach my $p (@$arg_param) {
563 next if !$prop->{$p}; # just to be sure
564 my $pd = $prop->{$p};
565
566 $arg_hash->{$p} = 1;
567 $args .= " " if $args;
568 if ($pd->{format} && $pd->{format} =~ m/-list/) {
569 $args .= "{<$p>}";
570 } else {
571 $args .= $pd->{optional} ? "[<$p>]" : "<$p>";
572 }
573 }
574
575 my $argdescr = '';
576 foreach my $k (@$arg_param) {
577 next if defined($fixed_param->{$k}); # just to be sure
578 next if !$prop->{$k}; # just to be sure
579 $argdescr .= &$get_property_description($k, 'fixed', $prop->{$k}, $format, 0);
580 }
581
582 my $idx_param = {}; # -vlan\d+ -scsi\d+
583
584 my $opts = '';
585 foreach my $k (sort keys %$prop) {
586 next if $arg_hash->{$k};
587 next if defined($fixed_param->{$k});
588
589 my $type_text = $prop->{$k}->{type} || 'string';
590
591 next if $hidepw && ($k eq 'password') && !$prop->{$k}->{optional};
592
593 my $base = $k;
594 if ($k =~ m/^([a-z]+)(\d+)$/) {
595 my ($name, $idx) = ($1, $2);
596 next if $idx_param->{$name};
597 if ($idx == 0 && defined($prop->{"${name}1"})) {
598 $idx_param->{$name} = 1;
599 $base = "${name}[n]";
600 }
601 }
602
603 my $param_mapping_hash = $compute_param_mapping_hash->(&$stringfilemap($name))
604 if $stringfilemap;
605
606 $opts .= &$get_property_description($base, 'arg', $prop->{$k}, $format,
607 $hidepw, $param_mapping_hash->{$k});
608
609 if (!$prop->{$k}->{optional}) {
610 $args .= " " if $args;
611 $args .= "--$base <$type_text>"
612 }
613 }
614
615 if ($format eq 'asciidoc') {
616 $out .= "*${prefix}*";
617 $out .= " `$args`" if $args;
618 $out .= $opts ? " `[OPTIONS]`\n" : "\n";
619 } else {
620 $out .= "USAGE: " if $format ne 'short';
621 $out .= "$prefix $args";
622 $out .= $opts ? " [OPTIONS]\n" : "\n";
623 }
624
625 return $out if $format eq 'short';
626
627 if ($info->{description}) {
628 if ($format eq 'asciidoc') {
629 my $desc = Text::Wrap::wrap('', '', ($info->{description}));
630 $out .= "\n$desc\n\n";
631 } elsif ($format eq 'full') {
632 my $desc = Text::Wrap::wrap(' ', ' ', ($info->{description}));
633 $out .= "\n$desc\n\n";
634 }
635 }
636
637 $out .= $argdescr if $argdescr;
638
639 $out .= $opts if $opts;
640
641 return $out;
642 }
643
644 # generate docs from JSON schema properties
645 sub dump_properties {
646 my ($prop, $format, $style, $filterFn) = @_;
647
648 my $raw = '';
649
650 $style //= 'config';
651
652 my $idx_param = {}; # -vlan\d+ -scsi\d+
653
654 foreach my $k (sort keys %$prop) {
655 my $phash = $prop->{$k};
656
657 next if defined($filterFn) && &$filterFn($k, $phash);
658 next if $phash->{alias};
659
660 my $base = $k;
661 if ($k =~ m/^([a-z]+)(\d+)$/) {
662 my ($name, $idx) = ($1, $2);
663 next if $idx_param->{$name};
664 if ($idx == 0 && defined($prop->{"${name}1"})) {
665 $idx_param->{$name} = 1;
666 $base = "${name}[n]";
667 }
668 }
669
670 $raw .= &$get_property_description($base, $style, $phash, $format, 0);
671
672 next if $style ne 'config';
673
674 my $prop_fmt = $phash->{format};
675 next if !$prop_fmt;
676
677 if (ref($prop_fmt) ne 'HASH') {
678 $prop_fmt = PVE::JSONSchema::get_format($prop_fmt);
679 }
680
681 next if !(ref($prop_fmt) && (ref($prop_fmt) eq 'HASH'));
682
683 $raw .= dump_properties($prop_fmt, $format, 'config-sub')
684
685 }
686
687 return $raw;
688 }
689
690 my $replace_file_names_with_contents = sub {
691 my ($param, $param_mapping_hash) = @_;
692
693 while (my ($k, $d) = each %$param_mapping_hash) {
694 $param->{$k} = $d->{func}->($param->{$k})
695 if defined($param->{$k});
696 }
697
698 return $param;
699 };
700
701 sub cli_handler {
702 my ($self, $prefix, $name, $args, $arg_param, $fixed_param, $pwcallback, $stringfilemap) = @_;
703
704 my $info = $self->map_method_by_name($name);
705
706 my $res;
707 eval {
708 my $param = PVE::JSONSchema::get_options($info->{parameters}, $args, $arg_param, $fixed_param, $pwcallback);
709
710 if (defined($stringfilemap)) {
711 my $param_mapping_hash = $compute_param_mapping_hash->(&$stringfilemap($name));
712 &$replace_file_names_with_contents($param, $param_mapping_hash);
713 }
714
715 $res = $self->handle($info, $param);
716 };
717 if (my $err = $@) {
718 my $ec = ref($err);
719
720 die $err if !$ec || $ec ne "PVE::Exception" || !$err->is_param_exc();
721
722 $err->{usage} = $self->usage_str($name, $prefix, $arg_param, $fixed_param, 'short', $pwcallback, $stringfilemap);
723
724 die $err;
725 }
726
727 return $res;
728 }
729
730 # utility methods
731 # note: this modifies the original hash by adding the id property
732 sub hash_to_array {
733 my ($hash, $idprop) = @_;
734
735 my $res = [];
736 return $res if !$hash;
737
738 foreach my $k (keys %$hash) {
739 $hash->{$k}->{$idprop} = $k;
740 push @$res, $hash->{$k};
741 }
742
743 return $res;
744 }
745
746 1;