]> git.proxmox.com Git - pve-common.git/blame - data/PVE/RESTHandler.pm
correctly copy bridge config
[pve-common.git] / data / PVE / RESTHandler.pm
CommitLineData
e143e9d8
DM
1package PVE::RESTHandler;
2
3use strict;
4no strict 'refs'; # our autoload requires this
e143e9d8
DM
5use warnings;
6use PVE::SafeSyslog;
7use PVE::Exception qw(raise raise_param_exc);
8use PVE::JSONSchema;
9use PVE::PodParser;
10use HTTP::Status qw(:constants :is status_message);
11use Text::Wrap;
12use Storable qw(dclone);
13
14my $method_registry = {};
15my $method_by_name = {};
16
17our $AUTOLOAD; # it's a package global
18
19sub api_clone_schema {
20 my ($schema) = @_;
21
22 my $res = {};
23 my $ref = ref($schema);
24 die "not a HASH reference" if !($ref && $ref eq 'HASH');
25
26 foreach my $k (keys %$schema) {
27 my $d = $schema->{$k};
28 if ($k ne 'properties') {
29 $res->{$k} = ref($d) ? dclone($d) : $d;
30 next;
31 }
32 # convert indexed parameters like -net\d+ to -net[n]
33 foreach my $p (keys %$d) {
34 my $pd = $d->{$p};
35 if ($p =~ m/^([a-z]+)(\d+)$/) {
36 if ($2 == 0) {
37 $p = "$1\[n\]";
38 } else {
39 next;
40 }
41 }
42 $res->{$k}->{$p} = ref($pd) ? dclone($pd) : $pd;
43 }
44 }
45
46 return $res;
47}
48
49sub api_dump_full {
50 my ($tree, $index, $class, $prefix) = @_;
51
52 $prefix = '' if !$prefix;
53
54 my $ma = $method_registry->{$class};
55
56 foreach my $info (@$ma) {
57
58 my $path = "$prefix/$info->{path}";
59 $path =~ s/\/+$//;
60
61 if ($info->{subclass}) {
62 api_dump_full($tree, $index, $info->{subclass}, $path);
63 } else {
64 next if !$path;
65
66 # check if method is unique
67 my $realpath = $path;
68 $realpath =~ s/\{[^\}]+\}/\{\}/g;
69 my $fullpath = "$info->{method} $realpath";
70 die "duplicate path '$realpath'" if $index->{$fullpath};
71 $index->{$fullpath} = $info;
72
73 # insert into tree
74 my $treedir = $tree;
75 my $res;
76 my $sp = '';
77 foreach my $dir (split('/', $path)) {
78 next if !$dir;
79 $sp .= "/$dir";
80 $res = (grep { $_->{text} eq $dir } @$treedir)[0];
81 if ($res) {
82 $res->{children} = [] if !$res->{children};
83 $treedir = $res->{children};
84 } else {
85 $res = {
86 path => $sp,
87 text => $dir,
88 children => [],
89 };
90 push @$treedir, $res;
91 $treedir = $res->{children};
92 }
93 }
94
95 if ($res) {
96 my $data = {};
97 foreach my $k (keys %$info) {
98 next if $k eq 'code' || $k eq "match_name" || $k eq "match_re" ||
99 $k eq "path";
100
101 my $d = $info->{$k};
102
103 if ($k eq 'parameters') {
104 $data->{$k} = api_clone_schema($d);
105 } else {
106
107 $data->{$k} = ref($d) ? dclone($d) : $d;
108 }
109 }
110 $res->{info}->{$info->{method}} = $data;
111 };
112 }
113 }
114};
115
116sub api_dump_cleanup_tree {
117 my ($tree) = @_;
118
119 foreach my $rec (@$tree) {
120 delete $rec->{children} if $rec->{children} && !scalar(@{$rec->{children}});
121 if ($rec->{children}) {
122 $rec->{leaf} = 0;
123 api_dump_cleanup_tree($rec->{children});
124 } else {
125 $rec->{leaf} = 1;
126 }
127 }
128
129}
130
131sub api_dump {
132 my ($class, $prefix) = @_;
133
134 my $tree = [];
135
136 my $index = {};
137 api_dump_full($tree, $index, $class);
138 api_dump_cleanup_tree($tree);
139 return $tree;
140};
141
142sub validate_method_schemas {
143
144 foreach my $class (keys %$method_registry) {
145 my $ma = $method_registry->{$class};
146
147 foreach my $info (@$ma) {
148 PVE::JSONSchema::validate_method_info($info);
149 }
150 }
151}
152
153sub register_method {
154 my ($self, $info) = @_;
155
156 my $match_re = [];
157 my $match_name = [];
158
159 foreach my $comp (split(/\/+/, $info->{path})) {
160 die "path compoment has zero length" if $comp eq '';
161 if ($comp =~ m/^\{(\w+)(:(.*))?\}$/) {
162 my $name = $1;
163 push @$match_re, $3 ? $3 : '\S+';
164 push @$match_name, $1;
165 } else {
166 push @$match_re, $comp;
167 push @$match_name, undef;
168 }
169 }
170
171 $info->{match_re} = $match_re;
172 $info->{match_name} = $match_name;
173
174 $method_by_name->{$self} = {} if !defined($method_by_name->{$self});
175
176 if ($info->{name}) {
177 die "method '${self}::$info->{name}' already defined\n"
178 if defined($method_by_name->{$self}->{$info->{name}});
179
180 $method_by_name->{$self}->{$info->{name}} = $info;
181 }
182
183 push @{$method_registry->{$self}}, $info;
184}
185
186sub AUTOLOAD {
187 my ($this) = @_;
188
189 # also see "man perldiag"
190
191 my $sub = $AUTOLOAD;
192 (my $method = $sub) =~ s/.*:://;
193
194 $method =~ s/.*:://;
195
196 my $info = $this->map_method_by_name($method);
197
198 *{$sub} = sub {
199 my $self = shift;
200 return $self->handle($info, @_);
201 };
202 goto &$AUTOLOAD;
203}
204
205sub method_attributes {
206 my ($self) = @_;
207
208 return $method_registry->{$self};
209}
210
211sub map_method_by_name {
212 my ($self, $name) = @_;
213
214 my $info = $method_by_name->{$self}->{$name};
215 die "no such method '${self}::$name'\n" if !$info;
216
217 return $info;
218}
219
220sub map_method {
221 my ($self, $stack, $method, $uri_param) = @_;
222
223 my $ma = $method_registry->{$self};
224
225 my $stacklen = scalar(@$stack);
226
227 #syslog ('info', "MAPTEST:$method:$self: " . join ('/', @$stack));
228
229 foreach my $info (@$ma) {
230 #syslog ('info', "TEST0 " . Dumper($info));
231 next if !($info->{subclass} || ($info->{method} eq $method));
232 my $regexlen = scalar(@{$info->{match_re}});
233 if ($info->{subclass}) {
234 next if $stacklen < $regexlen;
235 } else {
236 next if $stacklen != $regexlen;
237 }
238
239 #syslog ('info', "TEST1 " . Dumper($info));
240
241 my $param = {};
242 my $i = 0;
243 for (; $i < $regexlen; $i++) {
244 my $comp = $stack->[$i];
245 my $re = $info->{match_re}->[$i];
246 #print "COMPARE $comp $info->{match_re}->[$i]\n";
247 my ($match) = $stack->[$i] =~ m/^($re)$/;
248 last if !defined($match);
249 if (my $name = $info->{match_name}->[$i]) {
250 $param->{$name} = $match;
251 }
252 }
253
254 next if $i != $regexlen;
255
256 #print "MATCH $info->{name}\n";
257
258 foreach my $p (keys %$param) {
259 $uri_param->{$p} = $param->{$p};
260 }
261
262 return $info;
263 }
264}
265
266sub __find_handler_full {
267 my ($class, $method, $stack, $uri_param, $pathmatchref) = @_;
268
269 my $info;
270 eval {
271 $info = $class->map_method($stack, $method, $uri_param);
272 };
273 syslog('err', $@) if $@;
274
275 return undef if !$info;
276
277 $$pathmatchref .= '/' . $info->{path};
278
279 if (my $subh = $info->{subclass}) {
280
281 my $matchlen = scalar(@{$info->{match_re}});
282
283 for (my $i = 0; $i < $matchlen; $i++) {
284 shift @$stack; # pop from stack
285 }
286
287 my $fd = $info->{fragmentDelimiter};
288
289 if (defined($fd)) {
290
291 # we only support the empty string '' (match whole URI)
292 die "unsupported fragmentDelimiter '$fd'"
293 if $fd ne '';
294
295 $stack = [ join ('/', @$stack) ] if scalar(@$stack) > 1;
296 }
297
298 return $subh->__find_handler_full($method, $stack, $uri_param, $pathmatchref);
299 }
300
301 return ($class, $info, $$pathmatchref);
302};
303
304sub find_handler {
305 my ($class, $method, $path, $uri_param) = @_;
306
307 my $stack = [ grep { length($_) > 0 } split('\/+' , $path)]; # skip empty fragments
308
309 my $pathmatch = '';
310 return $class->__find_handler_full($method, $stack, $uri_param, \$pathmatch);
311}
312
313sub handle {
314 my ($self, $info, $param) = @_;
315
316 my $func = $info->{code};
317
318 if (!($info->{name} && $func)) {
319 raise("Method lookup failed ('$info->{name}')\n",
320 code => HTTP_INTERNAL_SERVER_ERROR);
321 }
322
323 if (my $schema = $info->{parameters}) {
324 # warn "validate ". Dumper($param}) . "\n" . Dumper($schema);
325 PVE::JSONSchema::validate($param, $schema);
326 # untaint data (already validated)
327 while (my ($key, $val) = each %$param) {
328 ($param->{$key}) = $val =~ /^(.*)$/s;
329 }
330 }
331
332 my $result = &$func($param);
333
334 # todo: this is only to be safe - disable?
335 if (my $schema = $info->{returns}) {
336 PVE::JSONSchema::validate($result, $schema, "Result verification vailed\n");
337 }
338
339 return $result;
340}
341
342# generate usage information for command line tools
343#
344# $name ... the name of the method
345# $prefix ... usually something like "$exename $cmd" ('pvesm add')
1d21344c
DM
346# $arg_param ... list of parameters we want to get as ordered arguments
347# on the command line (or single parameter name for lists)
e143e9d8
DM
348# $fixed_param ... do not generate and info about those parameters
349# $format:
350# 'long' ... default (list all options)
351# 'short' ... command line only (one line)
352# 'full' ... also include description
353# $hidepw ... hide password option (use this if you provide a read passwork callback)
354sub usage_str {
355 my ($self, $name, $prefix, $arg_param, $fixed_param, $format, $hidepw) = @_;
356
357 $format = 'long' if !$format;
358
359 my $info = $self->map_method_by_name($name);
360 my $schema = $info->{parameters};
361 my $prop = $schema->{properties};
362
363 my $out = '';
364
365 my $arg_hash = {};
366
367 my $args = '';
1d21344c
DM
368
369 $arg_param = [ $arg_param ] if $arg_param && !ref($arg_param);
370
e143e9d8
DM
371 foreach my $p (@$arg_param) {
372 next if !$prop->{$p}; # just to be sure
1d21344c 373 my $pd = $prop->{$p};
e143e9d8
DM
374
375 $arg_hash->{$p} = 1;
376 $args .= " " if $args;
1d21344c 377 if ($pd->{format} && $pd->{format} =~ m/-list/) {
7f0f0610 378 $args .= "{<$p>}";
1d21344c
DM
379 } else {
380 $args .= $pd->{optional} ? "[<$p>]" : "<$p>";
381 }
e143e9d8
DM
382 }
383
384 my $get_prop_descr = sub {
385 my ($k, $display_name) = @_;
386
387 my $phash = $prop->{$k};
388
389 my $res = '';
390
391 my $descr = $phash->{description} || "no description available";
392 chomp $descr;
393
394 my $type = PVE::PodParser::schema_get_type_text($phash);
395
396 if ($hidepw && $k eq 'password') {
397 $type = '';
398 }
399
400 my $defaulttxt = '';
401 if (defined(my $dv = $phash->{default})) {
402 $defaulttxt = " (default=$dv)";
403 }
404 my $tmp = sprintf " %-10s %s$defaulttxt\n", $display_name, "$type";
405 my $indend = " ";
406
407 $res .= Text::Wrap::wrap('', $indend, ($tmp));
408 $res .= "\n",
409 $res .= Text::Wrap::wrap($indend, $indend, ($descr)) . "\n\n";
410
411 if (my $req = $phash->{requires}) {
412 my $tmp = "Requires option(s): ";
413 $tmp .= ref($req) ? join(', ', @$req) : $req;
414 $res .= Text::Wrap::wrap($indend, $indend, ($tmp)). "\n\n";
415 }
416
417 return $res;
418 };
419
420 my $argdescr = '';
421 foreach my $k (@$arg_param) {
422 next if defined($fixed_param->{$k}); # just to be sure
423 next if !$prop->{$k}; # just to be sure
424 $argdescr .= &$get_prop_descr($k, "<$k>");
425 }
426
427 my $idx_param = {}; # -vlan\d+ -scsi\d+
428
429 my $opts = '';
430 foreach my $k (sort keys %$prop) {
431 next if $arg_hash->{$k};
432 next if defined($fixed_param->{$k});
433
434 my $type = $prop->{$k}->{type} || 'string';
435
436 next if $hidepw && ($k eq 'password') && !$prop->{$k}->{optional};
437
438 my $base = $k;
439 if ($k =~ m/^([a-z]+)(\d+)$/) {
440 my $name = $1;
441 next if $idx_param->{$name};
442 $idx_param->{$name} = 1;
443 $base = "${name}[n]";
444 }
445
446 $opts .= &$get_prop_descr($k, "-$base");
447
448 if (!$prop->{$k}->{optional}) {
449 $args .= " " if $args;
450 $args .= "-$base <$type>"
451 }
452 }
453
454 $out .= "USAGE: " if $format ne 'short';
455
456 $out .= "$prefix $args";
457
458 $out .= $opts ? " [OPTIONS]\n" : "\n";
459
460 return $out if $format eq 'short';
461
462 if ($info->{description} && $format eq 'full') {
463 my $desc = Text::Wrap::wrap(' ', ' ', ($info->{description}));
464 $out .= "\n$desc\n\n";
465 }
466
467 $out .= $argdescr if $argdescr;
468
469 $out .= $opts if $opts;
470
471 return $out;
472}
473
474sub cli_handler {
475 my ($self, $prefix, $name, $args, $arg_param, $fixed_param, $pwcallback) = @_;
476
477 my $info = $self->map_method_by_name($name);
478
e143e9d8
DM
479 my $res;
480 eval {
0ce82909 481 my $param = PVE::JSONSchema::get_options($info->{parameters}, $args, $arg_param, $fixed_param, $pwcallback);
e143e9d8
DM
482 $res = $self->handle($info, $param);
483 };
484 if (my $err = $@) {
485 my $ec = ref($err);
486
487 die $err if !$ec || $ec ne "PVE::Exception" || !$err->is_param_exc();
488
489 $err->{usage} = $self->usage_str($name, $prefix, $arg_param, $fixed_param, 'short', $pwcallback);
490
491 die $err;
492 }
493
494 return $res;
495}
496
497# utility methods
498# note: this modifies the original hash by adding the id property
499sub hash_to_array {
500 my ($hash, $idprop) = @_;
501
502 my $res = [];
503 return $res if !$hash;
504
505 foreach my $k (keys %$hash) {
506 $hash->{$k}->{$idprop} = $k;
507 push @$res, $hash->{$k};
508 }
509
510 return $res;
511}
512
5131;