This file is indexed.

/usr/lib/python3/dist-packages/gnocchi/resource_type.py is in python3-gnocchi 4.2.0-0ubuntu5.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# -*- encoding: utf-8 -*-
#
# 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 numbers
import re
import six
import stevedore
import voluptuous

from gnocchi import utils


INVALID_NAMES = [
    "id", "type", "metrics",
    "revision", "revision_start", "revision_end",
    "started_at", "ended_at",
    "user_id", "project_id",
    "created_by_user_id", "created_by_project_id", "get_metric",
    "creator",
]

VALID_CHARS = re.compile("[a-zA-Z0-9][a-zA-Z0-9_]*")


class InvalidResourceAttribute(ValueError):
    pass


class InvalidResourceAttributeName(InvalidResourceAttribute):
    """Error raised when the resource attribute name is invalid."""
    def __init__(self, name):
        super(InvalidResourceAttributeName, self).__init__(
            "Resource attribute name %s is invalid" % str(name))
        self.name = name


class InvalidResourceAttributeValue(InvalidResourceAttribute):
    """Error raised when the resource attribute min is greater than max"""
    def __init__(self, min, max):
        super(InvalidResourceAttributeValue, self).__init__(
            "Resource attribute value min (or min_length) %s must be less  "
            "than or equal to max (or max_length) %s!" % (str(min), str(max)))
        self.min = min
        self.max = max


class InvalidResourceAttributeOption(InvalidResourceAttribute):
    """Error raised when the resource attribute name is invalid."""
    def __init__(self, name, option, reason):
        super(InvalidResourceAttributeOption, self).__init__(
            "Option '%s' of resource attribute %s is invalid: %s" %
            (option, str(name), str(reason)))
        self.name = name
        self.option = option
        self.reason = reason


# NOTE(sileht): This is to store the behavior of some operations:
#  * fill, to set a default value to all existing resource type
#
# in the future for example, we can allow to change the length of
# a string attribute, if the new one is shorter, we can add a option
# to define the behavior like:
#  * resize = trunc or reject
OperationOptions = {
    voluptuous.Optional('fill'): object
}


class CommonAttributeSchema(object):
    meta_schema_ext = {}
    schema_ext = None

    def __init__(self, type, name, required, options=None):
        if (len(name) > 63 or name in INVALID_NAMES
                or not VALID_CHARS.match(name)):
            raise InvalidResourceAttributeName(name)

        self.name = name
        self.required = required
        self.fill = None

        # options is set only when we update a resource type
        if options is not None:
            fill = options.get("fill")
            if fill is None and required:
                raise InvalidResourceAttributeOption(
                    name, "fill", "must not be empty if required=True")
            elif fill is not None:
                # Ensure fill have the correct attribute type
                try:
                    self.fill = voluptuous.Schema(self.schema_ext)(fill)
                except voluptuous.Error as e:
                    raise InvalidResourceAttributeOption(name, "fill", e)

    @classmethod
    def meta_schema(cls, for_update=False):
        d = {
            voluptuous.Required('type'): cls.typename,
            voluptuous.Required('required', default=True): bool
        }
        if for_update:
            d[voluptuous.Required('options', default={})] = OperationOptions
        if callable(cls.meta_schema_ext):
            d.update(cls.meta_schema_ext())
        else:
            d.update(cls.meta_schema_ext)
        return d

    def schema(self):
        if self.required:
            return {self.name: self.schema_ext}
        else:
            return {voluptuous.Optional(self.name): self.schema_ext}

    def jsonify(self):
        return {"type": self.typename,
                "required": self.required}


class StringSchema(CommonAttributeSchema):
    typename = "string"

    def __init__(self, min_length, max_length, *args, **kwargs):
        if min_length > max_length:
            raise InvalidResourceAttributeValue(min_length, max_length)

        self.min_length = min_length
        self.max_length = max_length
        super(StringSchema, self).__init__(*args, **kwargs)

    meta_schema_ext = {
        voluptuous.Required('min_length', default=0):
        voluptuous.All(int, voluptuous.Range(min=0, max=255)),
        voluptuous.Required('max_length', default=255):
        voluptuous.All(int, voluptuous.Range(min=1, max=255))
    }

    @property
    def schema_ext(self):
        return voluptuous.All(six.text_type,
                              voluptuous.Length(
                                  min=self.min_length,
                                  max=self.max_length))

    def jsonify(self):
        d = super(StringSchema, self).jsonify()
        d.update({"max_length": self.max_length,
                  "min_length": self.min_length})
        return d


class UUIDSchema(CommonAttributeSchema):
    typename = "uuid"

    @staticmethod
    def schema_ext(value):
        try:
            return utils.UUID(value)
        except ValueError as e:
            raise voluptuous.Invalid(e)


class DatetimeSchema(CommonAttributeSchema):
    typename = "datetime"

    @staticmethod
    def schema_ext(value):
        try:
            return utils.to_datetime(value)
        except ValueError as e:
            raise voluptuous.Invalid(e)


class NumberSchema(CommonAttributeSchema):
    typename = "number"

    def __init__(self, min, max, *args, **kwargs):
        if max is not None and min is not None and min > max:
            raise InvalidResourceAttributeValue(min, max)
        self.min = min
        self.max = max
        super(NumberSchema, self).__init__(*args, **kwargs)

    meta_schema_ext = {
        voluptuous.Required('min', default=None): voluptuous.Any(
            None, numbers.Real),
        voluptuous.Required('max', default=None): voluptuous.Any(
            None, numbers.Real)
    }

    @property
    def schema_ext(self):
        return voluptuous.All(numbers.Real,
                              voluptuous.Range(min=self.min,
                                               max=self.max))

    def jsonify(self):
        d = super(NumberSchema, self).jsonify()
        d.update({"min": self.min, "max": self.max})
        return d


class BoolSchema(CommonAttributeSchema):
    typename = "bool"
    schema_ext = bool


class ResourceTypeAttributes(list):
    def jsonify(self):
        d = {}
        for attr in self:
            d[attr.name] = attr.jsonify()
        return d


class ResourceTypeSchemaManager(stevedore.ExtensionManager):
    def __init__(self, *args, **kwargs):
        super(ResourceTypeSchemaManager, self).__init__(*args, **kwargs)
        type_schemas = tuple([ext.plugin.meta_schema()
                              for ext in self.extensions])
        self._schema = voluptuous.Schema({
            "name": six.text_type,
            voluptuous.Required("attributes", default={}): {
                six.text_type: voluptuous.Any(*tuple(type_schemas))
            }
        })

        type_schemas = tuple([ext.plugin.meta_schema(for_update=True)
                              for ext in self.extensions])
        self._schema_for_update = voluptuous.Schema({
            "name": six.text_type,
            voluptuous.Required("attributes", default={}): {
                six.text_type: voluptuous.Any(*tuple(type_schemas))
            }
        })

    def __call__(self, definition):
        return self._schema(definition)

    def for_update(self, definition):
        return self._schema_for_update(definition)

    def attributes_from_dict(self, attributes):
        return ResourceTypeAttributes(
            self[attr["type"]].plugin(name=name, **attr)
            for name, attr in attributes.items())

    def resource_type_from_dict(self, name, attributes, state):
        return ResourceType(name, self.attributes_from_dict(attributes), state)


class ResourceType(object):
    def __init__(self, name, attributes, state):
        self.name = name
        self.attributes = attributes
        self.state = state

    @property
    def schema(self):
        schema = {}
        for attr in self.attributes:
            schema.update(attr.schema())
        return schema

    def __eq__(self, other):
        return self.name == other.name

    def jsonify(self):
        return {"name": self.name,
                "attributes": self.attributes.jsonify(),
                "state": self.state}