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