]> git.proxmox.com Git - pve-common.git/blobdiff - src/PVE/JSONSchema.pm
schema: take over 'pve-targetstorage' option
[pve-common.git] / src / PVE / JSONSchema.pm
index 15a498c019293682b7639aecc850d5021c4e4047..527e40980ffa86661484d0aa236f3e95861d68a9 100644 (file)
@@ -16,11 +16,14 @@ use Data::Dumper;
 use base 'Exporter';
 
 our @EXPORT_OK = qw(
+register_standard_option
 get_standard_option
 parse_property_string
-register_standard_option
+print_property_string
 );
 
+our $CONFIGID_RE = qr/[a-z][a-z0-9_-]+/i;
+
 # Note: This class implements something similar to JSON schema, but it is not 100% complete.
 # see: http://tools.ietf.org/html/draft-zyp-json-schema-02
 # see: http://json-schema.org/
@@ -80,6 +83,12 @@ register_standard_option('pve-storage-id', {
     type => 'string', format => 'pve-storage-id',
 });
 
+register_standard_option('pve-bridge-id', {
+    description => "Bridge to attach guest network devices to.",
+    type => 'string', format => 'pve-bridge-id',
+    format_description => 'bridge',
+});
+
 register_standard_option('pve-config-digest', {
     description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
     type => 'string',
@@ -121,19 +130,26 @@ register_standard_option('pve-snapshot-name', {
 });
 
 my $format_list = {};
+my $format_validators = {};
 
 sub register_format {
-    my ($format, $code) = @_;
+    my ($name, $format, $validator) = @_;
+
+    die "JSON schema format '$name' already registered\n"
+       if $format_list->{$name};
 
-    die "JSON schema format '$format' already registered\n"
-       if $format_list->{$format};
+    if ($validator) {
+       die "A \$validator function can only be specified for hash-based formats\n"
+           if ref($format) ne 'HASH';
+       $format_validators->{$name} = $validator;
+    }
 
-    $format_list->{$format} = $code;
+    $format_list->{$name} = $format;
 }
 
 sub get_format {
-    my ($format) = @_;
-    return $format_list->{$format};
+    my ($name) = @_;
+    return $format_list->{$name};
 }
 
 my $renderer_hash = {};
@@ -170,7 +186,7 @@ register_format('pve-configid', \&pve_verify_configid);
 sub pve_verify_configid {
     my ($id, $noerr) = @_;
 
-    if ($id !~ m/^[a-z][a-z0-9_-]+$/i) {
+    if ($id !~ m/^$CONFIGID_RE$/) {
        return undef if $noerr;
        die "invalid configuration ID '$id'\n";
     }
@@ -184,6 +200,17 @@ sub parse_storage_id {
     return parse_id($storeid, 'storage', $noerr);
 }
 
+PVE::JSONSchema::register_format('pve-bridge-id', \&parse_bridge_id);
+sub parse_bridge_id {
+    my ($id, $noerr) = @_;
+
+    if ($id !~ m/^[-_.\w\d]+$/) {
+       return undef if $noerr;
+       die "invalid bridge ID '$id'\n";
+    }
+    return $id;
+}
+
 PVE::JSONSchema::register_format('acme-plugin-id', \&parse_acme_plugin_id);
 sub parse_acme_plugin_id {
     my ($pluginid, $noerr) = @_;
@@ -223,6 +250,21 @@ sub pve_verify_node_name {
     return $node;
 }
 
+# maps source to target ID using an ID map
+sub map_id {
+    my ($map, $source) = @_;
+
+    return $source if !defined($map);
+
+    return $map->{entries}->{$source}
+       if $map->{entries} && defined($map->{entries}->{$source});
+
+    return $map->{default} if $map->{default};
+
+    # identity (fallback)
+    return $source;
+}
+
 sub parse_idmap {
     my ($idmap, $idformat) = @_;
 
@@ -264,20 +306,41 @@ sub parse_idmap {
     return $map;
 }
 
-register_format('storagepair', \&verify_storagepair);
-sub verify_storagepair {
-    my ($storagepair, $noerr) = @_;
+my $verify_idpair = sub {
+    my ($input, $noerr, $format) = @_;
 
-    # note: this only checks a single list entry
-    # when using a storagepair-list map, you need to pass the full
-    # parameter to parse_idmap
-    eval { parse_idmap($storagepair, 'pve-storage-id') };
+    eval { parse_idmap($input, $format) };
     if ($@) {
        return undef if $noerr;
        die "$@\n";
     }
 
-    return $storagepair;
+    return $input;
+};
+
+PVE::JSONSchema::register_standard_option('pve-targetstorage', {
+    description => "Mapping from source to target storages. Providing only a single storage ID maps all source storages to that storage. Providing the special value '1' will map each source storage to itself.",
+    type => 'string',
+    format => 'storage-pair-list',
+    optional => 1,
+});
+
+# note: this only checks a single list entry
+# when using a storage-pair-list map, you need to pass the full parameter to
+# parse_idmap
+register_format('storage-pair', \&verify_storagepair);
+sub verify_storagepair {
+    my ($storagepair, $noerr) = @_;
+    return $verify_idpair->($storagepair, $noerr, 'pve-storage-id');
+}
+
+# note: this only checks a single list entry
+# when using a bridge-pair-list map, you need to pass the full parameter to
+# parse_idmap
+register_format('bridge-pair', \&verify_bridgepair);
+sub verify_bridgepair {
+    my ($bridgepair, $noerr) = @_;
+    return $verify_idpair->($bridgepair, $noerr, 'pve-bridge-id');
 }
 
 register_format('mac-addr', \&pve_verify_mac_addr);
@@ -462,13 +525,25 @@ register_format('email', \&pve_verify_email);
 sub pve_verify_email {
     my ($email, $noerr) = @_;
 
-    if ($email !~ /^[\w\+\-\~]+(\.[\w\+\-\~]+)*@[a-zA-Z0-9\-]+(\.[a-zA-Z0-9\-]+)*$/) {
+    if ($email !~ /^$PVE::Tools::EMAIL_RE$/) {
           return undef if $noerr;
           die "value does not look like a valid email address\n";
     }
     return $email;
 }
 
+register_format('email-or-username', \&pve_verify_email_or_username);
+sub pve_verify_email_or_username {
+    my ($email, $noerr) = @_;
+
+    if ($email !~ /^$PVE::Tools::EMAIL_RE$/ &&
+       $email !~ /^$PVE::Tools::EMAIL_USER_RE$/) {
+          return undef if $noerr;
+          die "value does not look like a valid email address or user name\n";
+    }
+    return $email;
+}
+
 register_format('dns-name', \&pve_verify_dns_name);
 sub pve_verify_dns_name {
     my ($name, $noerr) = @_;
@@ -486,19 +561,19 @@ register_format('timezone', \&pve_verify_timezone);
 sub pve_verify_timezone {
     my ($timezone, $noerr) = @_;
 
-    my $zonetab = "/usr/share/zoneinfo/zone.tab";
     return $timezone if $timezone eq 'UTC';
-    open(my $fh, "<", $zonetab);
-    while(my $line = <$fh>) {
-       next if $line =~ /^#/;
+
+    open(my $fh, "<",  "/usr/share/zoneinfo/zone.tab");
+    while (my $line = <$fh>) {
+       next if $line =~ /^\s*#/;
        chomp $line;
-       return $timezone if $timezone eq (split /\t/, $line)[2]; # found
+       my $zone = (split /\t/, $line)[2];
+       return $timezone if $timezone eq $zone; # found
     }
     close $fh;
 
     return undef if $noerr;
     die "invalid time zone '$timezone'\n";
-
 }
 
 # network interface name
@@ -601,12 +676,41 @@ register_standard_option('bwlimit', {
     format => $bwlimit_format,
 });
 
+my $remote_format = {
+    host => {
+       type => 'string',
+       format_description => 'Remote Proxmox hostname or IP',
+    },
+    port => {
+       type => 'integer',
+       optional => 1,
+    },
+    apitoken => {
+       type => 'string',
+       format_description => 'A full Proxmox API token including the secret value.',
+    },
+    fingerprint => get_standard_option(
+       'fingerprint-sha256',
+       {
+           optional => 1,
+           format_description => 'Remote host\'s certificate fingerprint, if not trusted by system store.',
+       }
+    ),
+};
+register_format('proxmox-remote', $remote_format);
+register_standard_option('proxmox-remote', {
+    description => "Specification of a remote endpoint.",
+    type => 'string', format => 'proxmox-remote',
+});
+
+our $PVE_TAG_RE = qr/[a-z0-9_][a-z0-9_\-\+\.]*/i;
+
 # used for pve-tag-list in e.g., guest configs
 register_format('pve-tag', \&pve_verify_tag);
 sub pve_verify_tag {
     my ($value, $noerr) = @_;
 
-    return $value if $value =~ m/^[a-z0-9_][a-z0-9_\-\+\.]*$/i;
+    return $value if $value =~ m/^${PVE_TAG_RE}$/i;
 
     return undef if $noerr;
 
@@ -663,42 +767,63 @@ sub pve_verify_tfa_secret {
     die "unable to decode TFA secret\n";
 }
 
-sub check_format {
-    my ($format, $value, $path) = @_;
-
-    return parse_property_string($format, $value, $path) if ref($format) eq 'HASH';
-    return if $format eq 'regex';
-
-    if ($format =~ m/^(.*)-a?list$/) {
-
-       my $code = $format_list->{$1};
 
-       die "undefined format '$format'\n" if !$code;
+PVE::JSONSchema::register_format('pve-task-status-type', \&verify_task_status_type);
+sub verify_task_status_type {
+    my ($value, $noerr) = @_;
 
-       # Note: we allow empty lists
-       foreach my $v (split_list($value)) {
-           &$code($v);
-       }
+    return $value if $value =~ m/^(ok|error|warning|unknown)$/i;
 
-    } elsif ($format =~ m/^(.*)-opt$/) {
+    return undef if $noerr;
 
-       my $code = $format_list->{$1};
+    die "invalid status '$value'\n";
+}
 
-       die "undefined format '$format'\n" if !$code;
+sub check_format {
+    my ($format, $value, $path) = @_;
 
-       return if !$value; # allow empty string
+    if (ref($format) eq 'HASH') {
+       # hash ref cannot have validator/list/opt handling attached
+       return parse_property_string($format, $value, $path);
+    }
 
-       &$code($value);
+    if (ref($format) eq 'CODE') {
+       # we are the (sole, old-style) validator
+       return $format->($value);
+    }
 
-   } else {
+    return if $format eq 'regex';
 
-       my $code = $format_list->{$format};
+    my $parsed;
+    $format =~ m/^(.*?)(?:-a?(list|opt))?$/;
+    my ($format_name, $format_type) = ($1, $2 // 'none');
+    my $registered = get_format($format_name);
+    die "undefined format '$format'\n" if !$registered;
 
-       die "undefined format '$format'\n" if !$code;
+    die "'-$format_type' format must have code ref, not hash\n"
+       if $format_type ne 'none' && ref($registered) ne 'CODE';
 
-       return parse_property_string($code, $value, $path) if ref($code) eq 'HASH';
-       &$code($value);
+    if ($format_type eq 'list') {
+       $parsed = [];
+       # Note: we allow empty lists
+       foreach my $v (split_list($value)) {
+           push @{$parsed}, $registered->($v);
+       }
+    } elsif ($format_type eq 'opt') {
+       $parsed = $registered->($value) if $value;
+    } else {
+       if (ref($registered) eq 'HASH') {
+           # Note: this is the only case where a validator function could be
+           # attached, hence it's safe to handle that in parse_property_string.
+           # We do however have to call it with $format_name instead of
+           # $registered, so it knows about the name (and thus any validators).
+           $parsed = parse_property_string($format, $value, $path);
+       } else {
+           $parsed = $registered->($value);
+       }
     }
+
+    return $parsed;
 }
 
 sub parse_size {
@@ -754,9 +879,16 @@ sub parse_property_string {
     $additional_properties = 0 if !defined($additional_properties);
 
     # Support named formats here, too:
+    my $validator;
     if (!ref($format)) {
-       if (my $desc = $format_list->{$format}) {
-           $format = $desc;
+       if (my $reg = get_format($format)) {
+           die "parse_property_string only accepts hash based named formats\n"
+               if ref($reg) ne 'HASH';
+
+           # named formats can have validators attached
+           $validator = $format_validators->{$format};
+
+           $format = $reg;
        } else {
            die "unknown format: $format\n";
        }
@@ -812,6 +944,7 @@ sub parse_property_string {
        raise "format error\n", errors => $errors;
     }
 
+    return $validator->($res) if $validator;
     return $res;
 }
 
@@ -1141,7 +1274,10 @@ sub validate {
     # we can disable that in the final release
     # todo: is there a better/faster way to detect cycles?
     my $cycles = 0;
-    find_cycle($instance, sub { $cycles = 1 });
+    # 'download' responses can contain a filehandle, don't cycle-check that as
+    # it produces a warning
+    my $is_download = ref($instance) eq 'HASH' && exists($instance->{download});
+    find_cycle($instance, sub { $cycles = 1 }) if !$is_download;
     if ($cycles) {
        add_error($errors, undef, "data structure contains recursive cycles");
     } elsif ($schema) {
@@ -1590,7 +1726,8 @@ sub get_options {
            $opts->{$list_param} = $args;
            $args = [];
        } elsif (ref($arg_param)) {
-           foreach my $arg_name (@$arg_param) {
+           for (my $i = 0; $i < scalar(@$arg_param); $i++) {
+               my $arg_name = $arg_param->[$i];
                if ($opts->{'extra-args'}) {
                    raise("internal error: extra-args must be the last argument\n", code => HTTP_BAD_REQUEST);
                }
@@ -1599,7 +1736,19 @@ sub get_options {
                    $args = [];
                    next;
                }
-               raise("not enough arguments\n", code => HTTP_BAD_REQUEST) if !@$args;
+               if (!@$args) {
+                   # check if all left-over arg_param are optional, else we
+                   # must die as the mapping is then ambigious
+                   for (; $i < scalar(@$arg_param); $i++) {
+                       my $prop = $arg_param->[$i];
+                       raise("not enough arguments\n", code => HTTP_BAD_REQUEST)
+                           if !$schema->{properties}->{$prop}->{optional};
+                   }
+                   if ($arg_param->[-1] eq 'extra-args') {
+                       $opts->{'extra-args'} = [];
+                   }
+                   last;
+               }
                $opts->{$arg_name} = shift @$args;
            }
            raise("too many arguments\n", code => HTTP_BAD_REQUEST) if @$args;
@@ -1612,7 +1761,7 @@ sub get_options {
            foreach my $arg_name (@$arg_param) {
                if ($arg_name eq 'extra-args') {
                    $opts->{'extra-args'} = [];
-               } else {
+               } elsif (!$schema->{properties}->{$arg_name}->{optional}) {
                    raise("not enough arguments\n", code => HTTP_BAD_REQUEST);
                }
            }
@@ -1684,8 +1833,8 @@ sub get_options {
 }
 
 # A way to parse configuration data by giving a json schema
-sub parse_config {
-    my ($schema, $filename, $raw) = @_;
+sub parse_config : prototype($$$;$) {
+    my ($schema, $filename, $raw, $comment_key) = @_;
 
     # do fast check (avoid validate_schema($schema))
     die "got strange schema" if !$schema->{type} ||
@@ -1693,10 +1842,24 @@ sub parse_config {
 
     my $cfg = {};
 
+    my $comment_data;
+    my $handle_comment = sub { $_[0] =~ /^#/ };
+    if (defined($comment_key)) {
+       $comment_data = '';
+       my $comment_re = qr/^\Q$comment_key\E:\s*(.*\S)\s*$/;
+       $handle_comment = sub {
+           if ($_[0] =~ /^\#(.*)\s*$/ || $_[0] =~ $comment_re) {
+               $comment_data .= PVE::Tools::decode_text($1) . "\n";
+               return 1;
+           }
+           return undef;
+       };
+    }
+
     while ($raw =~ /^\s*(.+?)\s*$/gm) {
        my $line = $1;
 
-       next if $line =~ /^#/;
+       next if $handle_comment->($line);
 
        if ($line =~ m/^(\S+?):\s*(.*)$/) {
            my $key = $1;
@@ -1712,6 +1875,10 @@ sub parse_config {
        }
     }
 
+    if (defined($comment_data)) {
+       $cfg->{$comment_key} = $comment_data;
+    }
+
     my $errors = {};
     check_prop($cfg, $schema, '', $errors);
 
@@ -1874,9 +2041,12 @@ sub generate_typetext {
 sub print_property_string {
     my ($data, $format, $skip, $path) = @_;
 
+    my $validator;
     if (ref($format) ne 'HASH') {
        my $schema = get_format($format);
        die "not a valid format: $format\n" if !$schema;
+       # named formats can have validators attached
+       $validator = $format_validators->{$format};
        $format = $schema;
     }
 
@@ -1886,6 +2056,8 @@ sub print_property_string {
        raise "format error", errors => $errors;
     }
 
+    $data = $validator->($data) if $validator;
+
     my ($default_key, $keyAliasProps) = &$find_schema_default_key($format);
 
     my $res = '';