summaryrefslogtreecommitdiff
path: root/nova/api/validation/extra_specs/base.py
blob: 2597070127acc739ba37d84cc7e919456e1916c1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# Copyright 2020 Red Hat, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import dataclasses
import re
import typing as ty

from oslo_utils import strutils

from nova import exception


@dataclasses.dataclass
class ExtraSpecValidator:
    name: str
    description: str
    value: ty.Dict[str, ty.Any]
    deprecated: bool = False
    parameters: ty.List[ty.Dict[str, ty.Any]] = dataclasses.field(
        default_factory=list
    )

    name_regex: str = None
    value_regex: str = None

    def __post_init__(self):
        # generate a regex for the name

        name_regex = self.name
        # replace the human-readable patterns with named regex groups; this
        # will transform e.g. 'hw:numa_cpus.{id}' to 'hw:numa_cpus.(?P<id>\d+)'
        for param in self.parameters:
            pattern = f'(?P<{param["name"]}>{param["pattern"]})'
            name_regex = name_regex.replace(f'{{{param["name"]}}}', pattern)

        self.name_regex = name_regex

        # ...and do the same for the value, but only if we're using strings

        if self.value['type'] not in (int, str, bool):
            raise ValueError(
                f"Unsupported parameter type '{self.value['type']}'"
            )

        value_regex = None
        if self.value['type'] == str and self.value.get('pattern'):
            value_regex = self.value['pattern']

        self.value_regex = value_regex

    def _validate_str(self, value):
        if 'pattern' in self.value:
            value_match = re.fullmatch(self.value_regex, value)
            if not value_match:
                raise exception.ValidationError(
                    f"Validation failed; '{value}' is not of the format "
                    f"'{self.value_regex}'."
                )
        elif 'enum' in self.value:
            if value not in self.value['enum']:
                values = ', '.join(str(x) for x in self.value['enum'])
                raise exception.ValidationError(
                    f"Validation failed; '{value}' is not one of: {values}."
                )

    def _validate_int(self, value):
        try:
            value = int(value)
        except ValueError:
            raise exception.ValidationError(
                f"Validation failed; '{value}' is not a valid integer value."
            )

        if 'max' in self.value and self.value['max'] < value:
            raise exception.ValidationError(
                f"Validation failed; '{value}' is greater than the max value "
                f"of '{self.value['max']}'."
            )

        if 'min' in self.value and self.value['min'] > value:
            raise exception.ValidationError(
                f"Validation failed; '{value}' is less than the min value "
                f"of '{self.value['min']}'."
            )

    def _validate_bool(self, value):
        try:
            strutils.bool_from_string(value, strict=True)
        except ValueError:
            raise exception.ValidationError(
                f"Validation failed; '{value}' is not a valid boolean-like "
                f"value."
            )

    def validate(self, name, value):
        name_match = re.fullmatch(self.name_regex, name)
        if not name_match:
            # NOTE(stephenfin): This is mainly here for testing purposes
            raise exception.ValidationError(
                f"Validation failed; expected a name of format '{self.name}' "
                f"but got '{name}'."
            )

        if self.value['type'] == int:
            self._validate_int(value)
        elif self.value['type'] == bool:
            self._validate_bool(value)
        else:  # str
            self._validate_str(value)