]>
git.proxmox.com Git - pve-common.git/blob - src/PVE/JSONSchema.pm
1 package PVE
:: JSONSchema
;
5 use Storable
; # for dclone
7 use Devel
:: Cycle
- quiet
; # todo: remove?
8 use PVE
:: Tools
qw(split_list $IPV6RE $IPV4RE ) ;
9 use PVE
:: Exception
qw(raise) ;
10 use HTTP
:: Status
qw(:constants) ;
11 use Net
:: IP
qw(:PROC) ;
16 register_standard_option
20 # Note: This class implements something similar to JSON schema, but it is not 100% complete.
21 # see: http://tools.ietf.org/html/draft-zyp-json-schema-02
22 # see: http://json-schema.org/
24 # the code is similar to the javascript parser from http://code.google.com/p/jsonschema/
26 my $standard_options = {};
27 sub register_standard_option
{
28 my ( $name, $schema ) = @_ ;
30 die "standard option ' $name ' already registered \n "
31 if $standard_options ->{ $name };
33 $standard_options ->{ $name } = $schema ;
36 sub get_standard_option
{
37 my ( $name, $base ) = @_ ;
39 my $std = $standard_options ->{ $name };
40 die "no such standard option ' $name ' \n " if ! $std ;
42 my $res = $base || {};
44 foreach my $opt ( keys %$std ) {
45 next if defined ( $res ->{ $opt });
46 $res ->{ $opt } = $std ->{ $opt };
52 register_standard_option
( 'pve-vmid' , {
53 description
=> "The (unique) ID of the VM." ,
54 type
=> 'integer' , format
=> 'pve-vmid' ,
58 register_standard_option
( 'pve-node' , {
59 description
=> "The cluster node name." ,
60 type
=> 'string' , format
=> 'pve-node' ,
63 register_standard_option
( 'pve-node-list' , {
64 description
=> "List of cluster node names." ,
65 type
=> 'string' , format
=> 'pve-node-list' ,
68 register_standard_option
( 'pve-iface' , {
69 description
=> "Network interface name." ,
70 type
=> 'string' , format
=> 'pve-iface' ,
71 minLength
=> 2 , maxLength
=> 20 ,
74 register_standard_option
( 'pve-storage-id' , {
75 description
=> "The storage identifier." ,
76 type
=> 'string' , format
=> 'pve-storage-id' ,
79 register_standard_option
( 'pve-config-digest' , {
80 description
=> 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.' ,
83 maxLength
=> 40 , # sha1 hex digest lenght is 40
86 register_standard_option
( 'extra-args' , {
87 description
=> "Extra arguments as array" ,
89 items
=> { type
=> 'string' },
96 my ( $format, $code ) = @_ ;
98 die "JSON schema format ' $format ' already registered \n "
99 if $format_list ->{ $format };
101 $format_list ->{ $format } = $code ;
106 return $format_list ->{ $format };
109 # register some common type for pve
111 register_format
( 'string' , sub {}); # allow format => 'string-list'
113 register_format
( 'urlencoded' , \
& pve_verify_urlencoded
);
114 sub pve_verify_urlencoded
{
115 my ( $text, $noerr ) = @_ ;
116 if ( $text !~ /^[-%a-zA-Z0-9_.!~*'()]*$/ ) {
117 return undef if $noerr ;
118 die "invalid urlencoded string: $text\n " ;
123 register_format
( 'pve-configid' , \
& pve_verify_configid
);
124 sub pve_verify_configid
{
125 my ( $id, $noerr ) = @_ ;
127 if ( $id !~ m/^[a-z][a-z0-9_]+$/i ) {
128 return undef if $noerr ;
129 die "invalid configuration ID ' $id ' \n " ;
134 PVE
:: JSONSchema
:: register_format
( 'pve-storage-id' , \
& parse_storage_id
);
135 sub parse_storage_id
{
136 my ( $storeid, $noerr ) = @_ ;
138 if ( $storeid !~ m/^[a-z][a-z0-9\-\_\.]*[a-z0-9]$/i ) {
139 return undef if $noerr ;
140 die "storage ID ' $storeid ' contains illegal characters \n " ;
146 register_format
( 'pve-vmid' , \
& pve_verify_vmid
);
147 sub pve_verify_vmid
{
148 my ( $vmid, $noerr ) = @_ ;
150 if ( $vmid !~ m/^[1-9][0-9]{2,8}$/ ) {
151 return undef if $noerr ;
152 die "value does not look like a valid VM ID \n " ;
157 register_format
( 'pve-node' , \
& pve_verify_node_name
);
158 sub pve_verify_node_name
{
159 my ( $node, $noerr ) = @_ ;
161 if ( $node !~ m/^([a-zA-Z0-9]([a-zA-Z0-9\-]*[a-zA-Z0-9])?)$/ ) {
162 return undef if $noerr ;
163 die "value does not look like a valid node name \n " ;
168 register_format
( 'ipv4' , \
& pve_verify_ipv4
);
169 sub pve_verify_ipv4
{
170 my ( $ipv4, $noerr ) = @_ ;
172 if ( $ipv4 !~ m/^(?:$IPV4RE)$/ ) {
173 return undef if $noerr ;
174 die "value does not look like a valid IPv4 address \n " ;
179 register_format
( 'ipv6' , \
& pve_verify_ipv6
);
180 sub pve_verify_ipv6
{
181 my ( $ipv6, $noerr ) = @_ ;
183 if ( $ipv6 !~ m/^(?:$IPV6RE)$/ ) {
184 return undef if $noerr ;
185 die "value does not look like a valid IPv6 address \n " ;
190 register_format
( 'ip' , \
& pve_verify_ip
);
192 my ( $ip, $noerr ) = @_ ;
194 if ( $ip !~ m/^(?:(?:$IPV4RE)|(?:$IPV6RE))$/ ) {
195 return undef if $noerr ;
196 die "value does not look like a valid IP address \n " ;
201 my $ipv4_mask_hash = {
218 '255.255.128.0' => 17 ,
219 '255.255.192.0' => 18 ,
220 '255.255.224.0' => 19 ,
221 '255.255.240.0' => 20 ,
222 '255.255.248.0' => 21 ,
223 '255.255.252.0' => 22 ,
224 '255.255.254.0' => 23 ,
225 '255.255.255.0' => 24 ,
226 '255.255.255.128' => 25 ,
227 '255.255.255.192' => 26 ,
228 '255.255.255.224' => 27 ,
229 '255.255.255.240' => 28 ,
230 '255.255.255.248' => 29 ,
231 '255.255.255.252' => 30
234 register_format
( 'ipv4mask' , \
& pve_verify_ipv4mask
);
235 sub pve_verify_ipv4mask
{
236 my ( $mask, $noerr ) = @_ ;
238 if (! defined ( $ipv4_mask_hash ->{ $mask })) {
239 return undef if $noerr ;
240 die "value does not look like a valid IP netmask \n " ;
245 register_format
( 'CIDRv6' , \
& pve_verify_cidrv6
);
246 sub pve_verify_cidrv6
{
247 my ( $cidr, $noerr ) = @_ ;
249 if ( $cidr =~ m!^(?:$IPV6RE)(?:/(\d+))$! && ( $1 > 7 ) && ( $1 <= 120 )) {
253 return undef if $noerr ;
254 die "value does not look like a valid IPv6 CIDR network \n " ;
257 register_format
( 'CIDRv4' , \
& pve_verify_cidrv4
);
258 sub pve_verify_cidrv4
{
259 my ( $cidr, $noerr ) = @_ ;
261 if ( $cidr =~ m!^(?:$IPV4RE)(?:/(\d+))$! && ( $1 > 7 ) && ( $1 <= 32 )) {
265 return undef if $noerr ;
266 die "value does not look like a valid IPv4 CIDR network \n " ;
269 register_format
( 'CIDR' , \
& pve_verify_cidr
);
270 sub pve_verify_cidr
{
271 my ( $cidr, $noerr ) = @_ ;
273 if (!( pve_verify_cidrv4
( $cidr, 1 ) ||
274 pve_verify_cidrv6
( $cidr, 1 )))
276 return undef if $noerr ;
277 die "value does not look like a valid CIDR network \n " ;
283 register_format
( 'pve-ipv4-config' , \
& pve_verify_ipv4_config
);
284 sub pve_verify_ipv4_config
{
285 my ( $config, $noerr ) = @_ ;
287 return $config if $config =~ /^(?:dhcp|manual)$/ ||
288 pve_verify_cidrv4
( $config, 1 );
289 return undef if $noerr ;
290 die "value does not look like a valid ipv4 network configuration \n " ;
293 register_format
( 'pve-ipv6-config' , \
& pve_verify_ipv6_config
);
294 sub pve_verify_ipv6_config
{
295 my ( $config, $noerr ) = @_ ;
297 return $config if $config =~ /^(?:auto|dhcp|manual)$/ ||
298 pve_verify_cidrv6
( $config, 1 );
299 return undef if $noerr ;
300 die "value does not look like a valid ipv6 network configuration \n " ;
303 register_format
( 'email' , \
& pve_verify_email
);
304 sub pve_verify_email
{
305 my ( $email, $noerr ) = @_ ;
307 # we use same regex as in Utils.js
308 if ( $email !~ /^(\w+)([\-+.][\w]+)*@(\w[\-\w]*\.){1,5}([A-Za-z]){2,63}$/ ) {
309 return undef if $noerr ;
310 die "value does not look like a valid email address \n " ;
315 register_format
( 'dns-name' , \
& pve_verify_dns_name
);
316 sub pve_verify_dns_name
{
317 my ( $name, $noerr ) = @_ ;
319 my $namere = "([a-zA-Z0-9]([a-zA-Z0-9\-]*[a-zA-Z0-9])?)" ;
321 if ( $name !~ /^(${namere}\.)*${namere}$/ ) {
322 return undef if $noerr ;
323 die "value does not look like a valid DNS name \n " ;
328 # network interface name
329 register_format
( 'pve-iface' , \
& pve_verify_iface
);
330 sub pve_verify_iface
{
331 my ( $id, $noerr ) = @_ ;
333 if ( $id !~ m/^[a-z][a-z0-9_]{1,20}([:\.]\d+)?$/i ) {
334 return undef if $noerr ;
335 die "invalid network interface name ' $id ' \n " ;
340 # general addresses by name or IP
341 register_format
( 'address' , \
& pve_verify_address
);
342 sub pve_verify_address
{
343 my ( $addr, $noerr ) = @_ ;
345 if (!( pve_verify_ip
( $addr, 1 ) ||
346 pve_verify_dns_name
( $addr, 1 )))
348 return undef if $noerr ;
349 die "value does not look like a valid address: $addr\n " ;
354 register_format
( 'disk-size' , \
& pve_verify_disk_size
);
355 sub pve_verify_disk_size
{
356 my ( $size, $noerr ) = @_ ;
357 if (! defined ( parse_size
( $size ))) {
358 return undef if $noerr ;
359 die "value does not look like a valid disk size: $size\n " ;
364 register_standard_option
( 'spice-proxy' , {
365 description
=> "SPICE proxy server. This can be used by the client to specify the proxy server. All nodes in a cluster runs 'spiceproxy', so it is up to the client to choose one. By default, we return the node where the VM is currently running. As resonable setting is to use same node you use to connect to the API (This is window.location.hostname for the JS GUI)." ,
366 type
=> 'string' , format
=> 'address' ,
369 register_standard_option
( 'remote-viewer-config' , {
370 description
=> "Returned values can be directly passed to the 'remote-viewer' application." ,
371 additionalProperties
=> 1 ,
373 type
=> { type
=> 'string' },
374 password
=> { type
=> 'string' },
375 proxy
=> { type
=> 'string' },
376 host
=> { type
=> 'string' },
377 'tls-port' => { type
=> 'integer' },
381 register_format
( 'pve-startup-order' , \
& pve_verify_startup_order
);
382 sub pve_verify_startup_order
{
383 my ( $value, $noerr ) = @_ ;
385 return $value if pve_parse_startup_order
( $value );
387 return undef if $noerr ;
389 die "unable to parse startup options \n " ;
392 sub pve_parse_startup_order
{
395 return undef if ! $value ;
399 foreach my $p ( split ( /,/ , $value )) {
400 next if $p =~ m/^\s*$/ ;
402 if ( $p =~ m/^(order=)?(\d+)$/ ) {
404 } elsif ( $p =~ m/^up=(\d+)$/ ) {
406 } elsif ( $p =~ m/^down=(\d+)$/ ) {
416 PVE
:: JSONSchema
:: register_standard_option
( 'pve-startup-order' , {
417 description
=> "Startup and shutdown behavior. Order is a non-negative number defining the general startup order. Shutdown in done with reverse ordering. Additionally you can set the 'up' or 'down' delay in seconds, which specifies a delay to wait before the next VM is started or stopped." ,
419 type
=> 'string' , format
=> 'pve-startup-order' ,
420 typetext
=> '[[order=]\d+] [,up=\d+] [,down=\d+] ' ,
424 my ( $format, $value, $path ) = @_ ;
426 return parse_property_string
( $format, $value, $path ) if ref ( $format ) eq 'HASH' ;
427 return if $format eq 'regex' ;
429 if ( $format =~ m/^(.*)-a?list$/ ) {
431 my $code = $format_list ->{ $1 };
433 die "undefined format ' $format ' \n " if ! $code ;
435 # Note: we allow empty lists
436 foreach my $v ( split_list
( $value )) {
440 } elsif ( $format =~ m/^(.*)-opt$/ ) {
442 my $code = $format_list ->{ $1 };
444 die "undefined format ' $format ' \n " if ! $code ;
446 return if ! $value ; # allow empty string
452 my $code = $format_list ->{ $format };
454 die "undefined format ' $format ' \n " if ! $code ;
456 return parse_property_string
( $code, $value, $path ) if ref ( $code ) eq 'HASH' ;
464 return undef if $value !~ m/^(\d+(\.\d+)?)([KMGT])?$/ ;
465 my ( $size, $unit ) = ( $1, $3 );
468 $size = $size * 1024 ;
469 } elsif ( $unit eq 'M' ) {
470 $size = $size * 1024 * 1024 ;
471 } elsif ( $unit eq 'G' ) {
472 $size = $size * 1024 * 1024 * 1024 ;
473 } elsif ( $unit eq 'T' ) {
474 $size = $size * 1024 * 1024 * 1024 * 1024 ;
485 my $kb = int ( $size/1024 );
486 return $size if $kb*1024 != $size ;
488 my $mb = int ( $kb/1024 );
489 return "${kb}K" if $mb*1024 != $kb ;
491 my $gb = int ( $mb/1024 );
492 return "${mb}M" if $gb*1024 != $mb ;
494 my $tb = int ( $gb/1024 );
495 return "${gb}G" if $tb*1024 != $gb ;
500 sub parse_property_string
{
501 my ( $format, $data, $path, $additional_properties ) = @_ ;
503 # In property strings we default to not allowing additional properties
504 $additional_properties = 0 if ! defined ( $additional_properties );
509 foreach my $part ( split ( /,/ , $data )) {
510 next if $part =~ /^\s*$/ ;
512 if ( $part =~ /^([^=]+)=(.+)$/ ) {
513 my ( $k, $v ) = ( $1, $2 );
514 die "duplicate key in comma-separated list property: $k\n " if defined ( $res ->{ $k });
515 my $schema = $format ->{ $k };
516 if ( my $alias = $schema ->{ alias
}) {
518 $schema = $format ->{ $k };
520 die "invalid key in comma-separated list property: $k\n " if ! $schema ;
521 if ( $schema ->{ type
} && $schema ->{ type
} eq 'boolean' ) {
522 $v = 1 if $v =~ m/^(1|on|yes|true)$/i ;
523 $v = 0 if $v =~ m/^(0|off|no|false)$/i ;
526 } elsif ( $part !~ /=/ ) {
527 die "duplicate key in comma-separated list property: $default_key\n " if $default_key ;
528 foreach my $key ( keys %$format ) {
529 if ( $format ->{ $key }->{ default_key
}) {
531 if (! $res ->{ $default_key }) {
532 $res ->{ $default_key } = $part ;
535 die "duplicate key in comma-separated list property: $default_key\n " ;
538 die "value without key, but schema does not define a default key \n " if ! $default_key ;
540 die "missing key in comma-separated list property \n " ;
545 check_object
( $path, $format, $res, $additional_properties, $errors );
546 if ( scalar ( %$errors )) {
547 raise
"format error \n " , errors
=> $errors ;
553 sub print_property_string
{
554 my ( $data, $format, $skip, $path ) = @_ ;
556 if ( ref ( $format ) ne 'HASH' ) {
557 my $schema = $format_list ->{ $format };
558 die "not a valid format: $format\n " if ! $schema ;
563 check_object
( $path, $format, $data, undef , $errors );
564 if ( scalar ( %$errors )) {
565 raise
"format error" , errors
=> $errors ;
569 my %skipped = map { $_ => 1 } @$skip ;
571 my %required ; # this is a set, all present keys are required regardless of value
572 foreach my $key ( keys %$format ) {
574 if (! $format ->{ $key }->{ optional
} && ! $format ->{ $key }->{ alias
} && ! $skipped { $key }) {
579 if ( $format ->{ $key }->{ default_key
}) {
581 warn "multiple default keys in schema ( $default_key, $key ) \n " ;
591 $text = " $data ->{ $default_key }" ;
598 foreach my $key ( sort keys %$data ) {
599 delete $required { $key };
600 next if $skipped { $key };
601 die "invalid key: $key\n " if ! $allowed { $key };
603 my $typeformat = $format ->{ $key }->{ format
};
604 my $value = $data ->{ $key };
605 next if ! defined ( $value );
608 if ( $typeformat && $typeformat eq 'disk-size' ) {
609 $text .= " $key =" . format_size
( $value );
611 die "illegal value with commas for $key\n " if $value =~ /,/ ;
612 $text .= " $key = $value " ;
616 if ( my $missing = join ( ',' , keys %required )) {
617 die "missing properties: $missing\n " ;
624 my ( $errors, $path, $msg ) = @_ ;
626 $path = '_root' if ! $path ;
628 if ( $errors ->{ $path }) {
629 $errors ->{ $path } = join ( ' \n ' , $errors ->{ $path }, $msg );
631 $errors ->{ $path } = $msg ;
638 # see 'man perlretut'
639 return $value =~ /^[+-]?(\d+\.\d+|\d+\.|\.\d+|\d+)([eE][+-]?\d+)?$/ ;
645 return $value =~ m/^[+-]?\d+$/ ;
649 my ( $path, $type, $value, $errors ) = @_ ;
653 if (! defined ( $value )) {
654 return 1 if $type eq 'null' ;
658 if ( my $tt = ref ( $type )) {
659 if ( $tt eq 'ARRAY' ) {
660 foreach my $t ( @$type ) {
662 check_type
( $path, $t, $value, $tmperr );
663 return 1 if ! scalar ( %$tmperr );
665 my $ttext = join ( '|' , @$type );
666 add_error
( $errors, $path, "type check (' $ttext ') failed" );
668 } elsif ( $tt eq 'HASH' ) {
670 check_prop
( $value, $type, $path, $tmperr );
671 return 1 if ! scalar ( %$tmperr );
672 add_error
( $errors, $path, "type check failed" );
675 die "internal error - got reference type ' $tt '" ;
680 return 1 if $type eq 'any' ;
682 if ( $type eq 'null' ) {
683 if ( defined ( $value )) {
684 add_error
( $errors, $path, "type check (' $type ') failed - value is not null" );
690 my $vt = ref ( $value );
692 if ( $type eq 'array' ) {
693 if (! $vt || $vt ne 'ARRAY' ) {
694 add_error
( $errors, $path, "type check (' $type ') failed" );
698 } elsif ( $type eq 'object' ) {
699 if (! $vt || $vt ne 'HASH' ) {
700 add_error
( $errors, $path, "type check (' $type ') failed" );
704 } elsif ( $type eq 'coderef' ) {
705 if (! $vt || $vt ne 'CODE' ) {
706 add_error
( $errors, $path, "type check (' $type ') failed" );
712 add_error
( $errors, $path, "type check (' $type ') failed - got $vt " );
715 if ( $type eq 'string' ) {
716 return 1 ; # nothing to check ?
717 } elsif ( $type eq 'boolean' ) {
718 #if ($value =~ m/^(1|true|yes|on)$/i) {
721 #} elsif ($value =~ m/^(0|false|no|off)$/i) {
722 } elsif ( $value eq '0' ) {
725 add_error
( $errors, $path, "type check (' $type ') failed - got ' $value '" );
728 } elsif ( $type eq 'integer' ) {
729 if (! is_integer
( $value )) {
730 add_error
( $errors, $path, "type check (' $type ') failed - got ' $value '" );
734 } elsif ( $type eq 'number' ) {
735 if (! is_number
( $value )) {
736 add_error
( $errors, $path, "type check (' $type ') failed - got ' $value '" );
741 return 1 ; # no need to verify unknown types
751 my ( $path, $schema, $value, $additional_properties, $errors ) = @_ ;
753 # print "Check Object " . Dumper($value) . "\nSchema: " . Dumper($schema);
755 my $st = ref ( $schema );
756 if (! $st || $st ne 'HASH' ) {
757 add_error
( $errors, $path, "Invalid schema definition." );
761 my $vt = ref ( $value );
762 if (! $vt || $vt ne 'HASH' ) {
763 add_error
( $errors, $path, "an object is required" );
767 foreach my $k ( keys %$schema ) {
768 check_prop
( $value ->{ $k }, $schema ->{ $k }, $path ?
" $path . $k " : $k, $errors );
771 foreach my $k ( keys %$value ) {
773 my $newpath = $path ?
" $path . $k " : $k ;
775 if ( my $subschema = $schema ->{ $k }) {
776 if ( my $requires = $subschema ->{ requires
}) {
777 if ( ref ( $requires )) {
778 #print "TEST: " . Dumper($value) . "\n", Dumper($requires) ;
779 check_prop
( $value, $requires, $path, $errors );
780 } elsif (! defined ( $value ->{ $requires })) {
781 add_error
( $errors, $path ?
" $path . $requires " : $requires,
782 "missing property - ' $newpath ' requiers this property" );
786 next ; # value is already checked above
789 if ( defined ( $additional_properties ) && ! $additional_properties ) {
790 add_error
( $errors, $newpath, "property is not defined in schema " .
791 "and the schema does not allow additional properties" );
794 check_prop
( $value ->{ $k }, $additional_properties, $newpath, $errors )
795 if ref ( $additional_properties );
799 sub check_object_warn
{
800 my ( $path, $schema, $value, $additional_properties ) = @_ ;
802 check_object
( $path, $schema, $value, $additional_properties, $errors );
803 if ( scalar ( %$errors )) {
804 foreach my $k ( keys %$errors ) {
805 warn "parse error: $k : $errors ->{ $k } \n " ;
813 my ( $value, $schema, $path, $errors ) = @_ ;
815 die "internal error - no schema" if ! $schema ;
816 die "internal error" if ! $errors ;
818 #print "check_prop $path\n" if $value;
820 my $st = ref ( $schema );
821 if (! $st || $st ne 'HASH' ) {
822 add_error
( $errors, $path, "Invalid schema definition." );
826 # if it extends another schema, it must pass that schema as well
827 if ( $schema ->{ extends
}) {
828 check_prop
( $value, $schema ->{ extends
}, $path, $errors );
831 if (! defined ( $value )) {
832 return if $schema ->{ type
} && $schema ->{ type
} eq 'null' ;
833 if (! $schema ->{ optional
} && ! $schema ->{ alias
}) {
834 add_error
( $errors, $path, "property is missing and it is not optional" );
839 return if ! check_type
( $path, $schema ->{ type
}, $value, $errors );
841 if ( $schema ->{ disallow
}) {
843 if ( check_type
( $path, $schema ->{ disallow
}, $value, $tmperr )) {
844 add_error
( $errors, $path, "disallowed value was matched" );
849 if ( my $vt = ref ( $value )) {
851 if ( $vt eq 'ARRAY' ) {
852 if ( $schema ->{ items
}) {
853 my $it = ref ( $schema ->{ items
});
854 if ( $it && $it eq 'ARRAY' ) {
855 #die "implement me $path: $vt " . Dumper($schema) ."\n". Dumper($value);
856 die "not implemented" ;
859 foreach my $el ( @$value ) {
860 check_prop
( $el, $schema ->{ items
}, "${path}[ $ind ]" , $errors );
866 } elsif ( $schema ->{ properties
} || $schema ->{ additionalProperties
}) {
867 check_object
( $path, defined ( $schema ->{ properties
}) ?
$schema ->{ properties
} : {},
868 $value, $schema ->{ additionalProperties
}, $errors );
874 if ( my $format = $schema ->{ format
}) {
875 eval { check_format
( $format, $value, $path ); };
877 add_error
( $errors, $path, "invalid format - $@ " );
882 if ( my $pattern = $schema ->{ pattern
}) {
883 if ( $value !~ m/^$pattern$/ ) {
884 add_error
( $errors, $path, "value does not match the regex pattern" );
889 if ( defined ( my $max = $schema ->{ maxLength
})) {
890 if ( length ( $value ) > $max ) {
891 add_error
( $errors, $path, "value may only be $max characters long" );
896 if ( defined ( my $min = $schema ->{ minLength
})) {
897 if ( length ( $value ) < $min ) {
898 add_error
( $errors, $path, "value must be at least $min characters long" );
903 if ( is_number
( $value )) {
904 if ( defined ( my $max = $schema ->{ maximum
})) {
906 add_error
( $errors, $path, "value must have a maximum value of $max " );
911 if ( defined ( my $min = $schema ->{ minimum
})) {
913 add_error
( $errors, $path, "value must have a minimum value of $min " );
919 if ( my $ea = $schema ->{ enum
}) {
922 foreach my $ev ( @$ea ) {
929 add_error
( $errors, $path, "value ' $value ' does not have a value in the enumeration '" .
930 join ( ", " , @$ea ) . "'" );
937 my ( $instance, $schema, $errmsg ) = @_ ;
940 $errmsg = "Parameter verification failed. \n " if ! $errmsg ;
942 # todo: cycle detection is only needed for debugging, I guess
943 # we can disable that in the final release
944 # todo: is there a better/faster way to detect cycles?
946 find_cycle
( $instance, sub { $cycles = 1 });
948 add_error
( $errors, undef , "data structure contains recursive cycles" );
950 check_prop
( $instance, $schema, '' , $errors );
953 if ( scalar ( %$errors )) {
954 raise
$errmsg, code
=> HTTP_BAD_REQUEST
, errors
=> $errors ;
960 my $schema_valid_types = [ "string" , "object" , "coderef" , "array" , "boolean" , "number" , "integer" , "null" , "any" ];
961 my $default_schema_noref = {
962 description
=> "This is the JSON Schema for JSON Schemas." ,
963 type
=> [ "object" ],
964 additionalProperties
=> 0 ,
967 type
=> [ "string" , "array" ],
968 description
=> "This is a type definition value. This can be a simple type, or a union type" ,
973 enum
=> $schema_valid_types,
975 enum
=> $schema_valid_types,
979 description
=> "This indicates that the instance property in the instance object is not required." ,
985 description
=> "This is a definition for the properties of an object value" ,
991 description
=> "When the value is an array, this indicates the schema to use to validate each item in an array" ,
995 additionalProperties
=> {
996 type
=> [ "boolean" , "object" ],
997 description
=> "This provides a default property definition for all properties that are not explicitly defined in an object type definition." ,
1004 description
=> "This indicates the minimum value for the instance property when the type of the instance value is a number." ,
1009 description
=> "This indicates the maximum value for the instance property when the type of the instance value is a number." ,
1013 description
=> "When the instance value is a string, this indicates minimum length of the string" ,
1020 description
=> "When the instance value is a string, this indicates maximum length of the string." ,
1026 description
=> "A text representation of the type (used to generate documentation)." ,
1031 description
=> "When the instance value is a string, this provides a regular expression that a instance string value should match in order to be valid." ,
1038 description
=> "This provides an enumeration of possible values that are valid for the instance property." ,
1043 description
=> "This provides a description of the purpose the instance property. The value can be a string or it can be an object with properties corresponding to various different instance languages (with an optional default property indicating the default description)." ,
1045 format_description
=> {
1048 description
=> "This provides a shorter (usually just one word) description for a property used to generate descriptions for comma separated list property strings." ,
1053 description
=> "This provides the title of the property" ,
1056 type
=> [ "string" , "object" ],
1058 description
=> "indicates a required property or a schema that must be validated if this property is present" ,
1061 type
=> [ "string" , "object" ],
1063 description
=> "This indicates what format the data is among some predefined formats which may include: \n\n date - a string following the ISO format \n address \n schema - a schema definition object \n person \n page \n html - a string representing HTML" ,
1068 description
=> "Whether this is the default key in a comma separated list property string." ,
1073 description
=> "When a key represents the same property as another it can be an alias to it, causing the parsed datastructure to use the other key to store the current value under." ,
1078 description
=> "This indicates the default for the instance property."
1082 description
=> "Bash completion function. This function should return a list of possible values." ,
1088 description
=> "This attribute may take the same values as the \" type \" attribute, however if the instance matches the type or if this value is an array and the instance matches any type or schema in the array, then this instance is not valid." ,
1093 description
=> "This indicates the schema extends the given schema. All instances of this schema must be valid to by the extended schema also." ,
1096 # this is from hyper schema
1099 description
=> "This defines the link relations of the instance objects" ,
1106 description
=> "This defines the target URL for the relation and can be parameterized using {propertyName} notation. It should be resolved as a URI-reference relative to the URI that was used to retrieve the instance document" ,
1110 description
=> "This is the name of the link relation" ,
1116 description
=> "For submission links, this defines the method that should be used to access the target resource" ,
1126 my $default_schema = Storable
:: dclone
( $default_schema_noref );
1128 $default_schema ->{ properties
}->{ properties
}->{ additionalProperties
} = $default_schema ;
1129 $default_schema ->{ properties
}->{ additionalProperties
}->{ properties
} = $default_schema ->{ properties
};
1131 $default_schema ->{ properties
}->{ items
}->{ properties
} = $default_schema ->{ properties
};
1132 $default_schema ->{ properties
}->{ items
}->{ additionalProperties
} = 0 ;
1134 $default_schema ->{ properties
}->{ disallow
}->{ properties
} = $default_schema ->{ properties
};
1135 $default_schema ->{ properties
}->{ disallow
}->{ additionalProperties
} = 0 ;
1137 $default_schema ->{ properties
}->{ requires
}->{ properties
} = $default_schema ->{ properties
};
1138 $default_schema ->{ properties
}->{ requires
}->{ additionalProperties
} = 0 ;
1140 $default_schema ->{ properties
}->{ extends
}->{ properties
} = $default_schema ->{ properties
};
1141 $default_schema ->{ properties
}->{ extends
}->{ additionalProperties
} = 0 ;
1143 my $method_schema = {
1145 additionalProperties
=> 0 ,
1148 description
=> "This a description of the method" ,
1153 description
=> "This indicates the name of the function to call." ,
1156 additionalProperties
=> 1 ,
1171 description
=> "The HTTP method name." ,
1172 enum
=> [ 'GET' , 'POST' , 'PUT' , 'DELETE' ],
1177 description
=> "Method needs special privileges - only pvedaemon can execute it" ,
1182 description
=> "A parameter name. If specified, all calls to this method are proxied to the host contained in that parameter." ,
1187 description
=> "Required access permissions. By default only 'root' is allowed to access this method." ,
1189 additionalProperties
=> 0 ,
1192 description
=> "Describe access permissions." ,
1196 description
=> "A simply way to allow access for 'all' authenticated users. Value 'world' is used to allow access without credentials." ,
1198 enum
=> [ 'all' , 'world' ],
1202 description
=> "Array of permission checks (prefix notation)." ,
1209 description
=> "Used internally" ,
1213 description
=> "Used internally" ,
1218 description
=> "path for URL matching (uri template)" ,
1220 fragmentDelimiter
=> {
1222 description
=> "A ways to override the default fragment delimiter '/'. This onyl works on a whole sub-class. You can set this to the empty string to match the whole rest of the URI." ,
1227 description
=> "JSON Schema for parameters." ,
1232 description
=> "Used to store page formatter information (set by PVE::RESTHandler->register_page_formatter)." ,
1237 description
=> "JSON Schema for return value." ,
1242 description
=> "method implementaion (code reference)" ,
1247 description
=> "Delegate call to this class (perl class string)." ,
1250 additionalProperties
=> 0 ,
1256 fragmentDelimiter
=> { optional
=> 1 }
1264 sub validate_schema
{
1267 my $errmsg = "internal error - unable to verify schema \n " ;
1268 validate
( $schema, $default_schema, $errmsg );
1271 sub validate_method_info
{
1274 my $errmsg = "internal error - unable to verify method info \n " ;
1275 validate
( $info, $method_schema, $errmsg );
1277 validate_schema
( $info ->{ parameters
}) if $info ->{ parameters
};
1278 validate_schema
( $info ->{ returns
}) if $info ->{ returns
};
1281 # run a self test on load
1282 # make sure we can verify the default schema
1283 validate_schema
( $default_schema_noref );
1284 validate_schema
( $method_schema );
1286 # and now some utility methods (used by pve api)
1287 sub method_get_child_link
{
1290 return undef if ! $info ;
1292 my $schema = $info ->{ returns
};
1293 return undef if ! $schema || ! $schema ->{ type
} || $schema ->{ type
} ne 'array' ;
1295 my $links = $schema ->{ links
};
1296 return undef if ! $links ;
1299 foreach my $lnk ( @$links ) {
1300 if ( $lnk ->{ href
} && $lnk ->{ rel
} && ( $lnk ->{ rel
} eq 'child' )) {
1309 # a way to parse command line parameters, using a
1310 # schema to configure Getopt::Long
1312 my ( $schema, $args, $arg_param, $fixed_param, $pwcallback ) = @_ ;
1314 if (! $schema || ! $schema ->{ properties
}) {
1315 raise
( "too many arguments \n " , code
=> HTTP_BAD_REQUEST
)
1316 if scalar ( @$args ) != 0 ;
1321 if ( $arg_param && ! ref ( $arg_param )) {
1322 my $pd = $schema ->{ properties
}->{ $arg_param };
1323 die "expected list format $pd ->{format}"
1324 if !( $pd && $pd ->{ format
} && $pd ->{ format
} =~ m/-list/ );
1325 $list_param = $arg_param ;
1329 foreach my $prop ( keys %{ $schema ->{ properties
}}) {
1330 my $pd = $schema ->{ properties
}->{ $prop };
1331 next if $list_param && $prop eq $list_param ;
1332 next if defined ( $fixed_param ->{ $prop });
1334 if ( $prop eq 'password' && $pwcallback ) {
1335 # we do not accept plain password on input line, instead
1336 # we turn this into a boolean option and ask for password below
1337 # using $pwcallback() (for security reasons).
1338 push @getopt, " $prop " ;
1339 } elsif ( $pd ->{ type
} eq 'boolean' ) {
1340 push @getopt, " $prop :s" ;
1342 if ( $pd ->{ format
} && $pd ->{ format
} =~ m/-a?list/ ) {
1343 push @getopt, " $prop =s@" ;
1345 push @getopt, " $prop =s" ;
1350 Getopt
:: Long
:: Configure
( 'prefix_pattern=(--|-)' );
1353 raise
( "unable to parse option \n " , code
=> HTTP_BAD_REQUEST
)
1354 if ! Getopt
:: Long
:: GetOptionsFromArray
( $args, $opts, @getopt );
1358 $opts ->{ $list_param } = $args ;
1360 } elsif ( ref ( $arg_param )) {
1361 foreach my $arg_name ( @$arg_param ) {
1362 if ( $opts ->{ 'extra-args' }) {
1363 raise
( "internal error: extra-args must be the last argument \n " , code
=> HTTP_BAD_REQUEST
);
1365 if ( $arg_name eq 'extra-args' ) {
1366 $opts ->{ 'extra-args' } = $args ;
1370 raise
( "not enough arguments \n " , code
=> HTTP_BAD_REQUEST
) if ! @$args ;
1371 $opts ->{ $arg_name } = shift @$args ;
1373 raise
( "too many arguments \n " , code
=> HTTP_BAD_REQUEST
) if @$args ;
1375 raise
( "too many arguments \n " , code
=> HTTP_BAD_REQUEST
)
1376 if scalar ( @$args ) != 0 ;
1380 if ( my $pd = $schema ->{ properties
}->{ password
}) {
1381 if ( $pd ->{ type
} ne 'boolean' && $pwcallback ) {
1382 if ( $opts ->{ password
} || ! $pd ->{ optional
}) {
1383 $opts ->{ password
} = & $pwcallback ();
1388 $opts = PVE
:: Tools
:: decode_utf8_parameters
( $opts );
1390 foreach my $p ( keys %$opts ) {
1391 if ( my $pd = $schema ->{ properties
}->{ $p }) {
1392 if ( $pd ->{ type
} eq 'boolean' ) {
1393 if ( $opts ->{ $p } eq '' ) {
1395 } elsif ( $opts ->{ $p } =~ m/^(1|true|yes|on)$/i ) {
1397 } elsif ( $opts ->{ $p } =~ m/^(0|false|no|off)$/i ) {
1400 raise
( "unable to parse boolean option \n " , code
=> HTTP_BAD_REQUEST
);
1402 } elsif ( $pd ->{ format
}) {
1404 if ( $pd ->{ format
} =~ m/-list/ ) {
1405 # allow --vmid 100 --vmid 101 and --vmid 100,101
1406 # allow --dow mon --dow fri and --dow mon,fri
1407 $opts ->{ $p } = join ( "," , @{ $opts ->{ $p }}) if ref ( $opts ->{ $p }) eq 'ARRAY' ;
1408 } elsif ( $pd ->{ format
} =~ m/-alist/ ) {
1409 # we encode array as \0 separated strings
1410 # Note: CGI.pm also use this encoding
1411 if ( scalar (@{ $opts ->{ $p }}) != 1 ) {
1412 $opts ->{ $p } = join ( "\0" , @{ $opts ->{ $p }});
1414 # st that split_list knows it is \0 terminated
1415 my $v = $opts ->{ $p }->[ 0 ];
1416 $opts ->{ $p } = " $v\0 " ;
1423 foreach my $p ( keys %$fixed_param ) {
1424 $opts ->{ $p } = $fixed_param ->{ $p };
1430 # A way to parse configuration data by giving a json schema
1432 my ( $schema, $filename, $raw ) = @_ ;
1434 # do fast check (avoid validate_schema($schema))
1435 die "got strange schema" if ! $schema ->{ type
} ||
1436 ! $schema ->{ properties
} || $schema ->{ type
} ne 'object' ;
1440 while ( $raw =~ /^\s*(.+?)\s*$/gm ) {
1443 next if $line =~ /^#/ ;
1445 if ( $line =~ m/^(\S+?):\s*(.*)$/ ) {
1448 if ( $schema ->{ properties
}->{ $key } &&
1449 $schema ->{ properties
}->{ $key }->{ type
} eq 'boolean' ) {
1451 $value = 1 if $value =~ m/^(1|on|yes|true)$/i ;
1452 $value = 0 if $value =~ m/^(0|off|no|false)$/i ;
1454 $cfg ->{ $key } = $value ;
1456 warn "ignore config line: $line\n "
1461 check_prop
( $cfg, $schema, '' , $errors );
1463 foreach my $k ( keys %$errors ) {
1464 warn "parse error in ' $filename ' - ' $k ': $errors ->{ $k } \n " ;
1471 # generate simple key/value file
1473 my ( $schema, $filename, $cfg ) = @_ ;
1475 # do fast check (avoid validate_schema($schema))
1476 die "got strange schema" if ! $schema ->{ type
} ||
1477 ! $schema ->{ properties
} || $schema ->{ type
} ne 'object' ;
1479 validate
( $cfg, $schema, "validation error in ' $filename ' \n " );
1483 foreach my $k ( keys %$cfg ) {
1484 $data .= " $k : $cfg ->{ $k } \n " ;