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