File: models.py

package info (click to toggle)
openstack-trove 1%3A24.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,976 kB
  • sloc: python: 50,665; sh: 2,866; makefile: 71
file content (459 lines) | stat: -rw-r--r-- 14,816 bytes parent folder | download | duplicates (2)
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
# Copyright 2016 Tesora, 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 abc

from trove.common import cfg
from trove.common.i18n import _
from trove.common import utils

CONF = cfg.CONF

"""
The classes below are generic and can be used for any datastore, but will not
provide validation. To add a new datastore create a sub-package (see mysql for
example) and create new child classes inheriting from these generic classes.

As a guideline, for new datastores the following class methods/variables should
be overridden if validation is desired (see their docstrings for additional
info):

DatastoreModelsBase:
        __init__

DatastoreSchema:
        _max_schema_name_length
        _is_valid_schema_name
        verify_dict
        _create_checks
        _delete_checks

DatastoreUser:
        _is_valid_user_name
        _is_valid_host_name
        _is_valid_password
        _is_valid_database
        verify_dict
        _create_checks
        _delete_checks
"""


class DatastoreModelsBase(object):
    """Base model for the datastore schema and user models."""

    def serialize(self):
        return self.__dict__

    def _deserialize(self, obj):
        self.__dict__ = obj

    def __repr__(self):
        return str(self.serialize())

    @classmethod
    def deserialize(cls, value, verify=True):
        item = cls(deserializing=True)
        item._deserialize(value)
        if verify:
            item.verify_dict()
        return item

    @abc.abstractmethod
    def verify_dict(self):
        """Validate the object's data dictionary.
        :returns:            True if dictionary is valid.
        """

    @staticmethod
    def check_string(value, desc):
        """Check if the value is a string/unicode.
        :param value:        Value to check.
        :param desc:         Description for exception message.
        :raises:             ValueError if not a string/unicode.
        """
        if not isinstance(value, str):
            raise ValueError(_("%(desc)s is not a string. Type = %(t)s.")
                             % {'desc': desc, 't': type(value)})


class DatastoreSchema(DatastoreModelsBase):
    """Represents a database schema."""

    def __init__(self, name=None, deserializing=False):
        self._name = None
        self._collate = None
        self._character_set = None
        # If both or neither are passed in this is a bug.
        if bool(deserializing) == bool(name):
            raise RuntimeError(_("Bug in DatastoreSchema()"))
        if not deserializing:
            self.name = name

    def __str__(self):
        return str(self.name)

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        self._validate_schema_name(value)
        self._name = value

    @property
    def collate(self):
        return self._collate

    @collate.setter
    def collate(self, value):
        if not value:
            pass
        else:
            self._collate = value

    @property
    def character_set(self):
        return self._character_set

    @character_set.setter
    def character_set(self, value):
        if not value:
            pass
        else:
            self._character_set = value

    def _validate_schema_name(self, value):
        """Perform checks on a given schema name.
        :param value:        Validated schema name.
        :type value:         string
        :raises:             ValueError On validation errors.
        """
        if not value:
            raise ValueError(_("Schema name empty."))
        self.check_string(value, 'Schema name')
        if self._max_schema_name_length and (len(value) >
                                             self._max_schema_name_length):
            raise ValueError(_("Schema name '%(name)s' is too long. "
                               "Max length = %(max_length)d.")
                             % {'name': value,
                                'max_length': self._max_schema_name_length})
        elif not self._is_valid_schema_name(value):
            raise ValueError(_("'%s' is not a valid schema name.") % value)

    @property
    def _max_schema_name_length(self):
        """Return the maximum valid schema name length if any.
        :returns:            Maximum schema name length or None if unlimited.
        """
        return None

    def _is_valid_schema_name(self, value):
        """Validate a given schema name.
        :param value:        Validated schema name.
        :type value:         string
        :returns:            TRUE if valid, FALSE otherwise.
        """
        return True

    def verify_dict(self):
        """Check that the object's dictionary values are valid by reloading
        them via the property setters. The checkers should raise the
        ValueError exception if invalid. All mandatory fields should be
        checked.
        """
        self.name = self._name

    @property
    def ignored_dbs(self):
        return cfg.get_ignored_dbs()

    def is_ignored(self):
        return self.name in self.ignored_dbs

    def check_reserved(self):
        """Check if the name is on the ignore_dbs list, meaning it is
        reserved.
        :raises:             ValueError if name is on the reserved list.
        """
        if self.is_ignored():
            raise ValueError(_('Database name "%(name)s" is on the reserved '
                               'list: %(reserved)s.')
                             % {'name': self.name,
                                'reserved': self.ignored_dbs})

    def _create_checks(self):
        """Checks to be performed before database can be created."""
        self.check_reserved()

    def check_create(self):
        """Check if the database can be created.
        :raises:             ValueError if the schema is not valid for create.
        """
        try:
            self._create_checks()
        except ValueError as e:
            raise ValueError(_('Cannot create database: %(error)s')
                             % {'error': str(e)})

    def _delete_checks(self):
        """Checks to be performed before database can be deleted."""
        self.check_reserved()

    def check_delete(self):
        """Check if the database can be deleted.
        :raises:             ValueError if the schema is not valid for delete.
        """
        try:
            self._delete_checks()
        except ValueError as e:
            raise ValueError(_('Cannot delete database: %(error)s')
                             % {'error': str(e)})


class DatastoreUser(DatastoreModelsBase):
    """Represents a datastore user."""

    _HOSTNAME_WILDCARD = '%'
    root_username = 'root'

    def __init__(self, name=None, password=None, host=None, databases=None,
                 deserializing=False):
        self._name = None
        self._password = None
        self._host = self._HOSTNAME_WILDCARD
        self._databases = []
        self._is_root = False
        if not deserializing:
            self.name = name
            if password:
                self.password = password
            if host:
                self.host = host
            if databases:
                self.databases = databases

    @classmethod
    def root(cls, name=None, password=None, *args, **kwargs):
        if not name:
            name = cls.root_username
        if not password:
            password = utils.generate_random_password()
        user = cls(name, password, *args, **kwargs)
        user.make_root()
        return user

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        self._validate_user_name(value)
        self._name = value

    @property
    def password(self):
        return self._password

    @password.setter
    def password(self, value):
        self.check_string(value, "User password")
        if self._is_valid_password(value):
            self._password = value
        else:
            raise ValueError(_("'%s' is not a valid password.") % value)

    def _add_database(self, value):
        serial_db = self._build_database_schema(value).serialize()
        if self._is_valid_database(serial_db):
            self._databases.append(serial_db)

    @property
    def databases(self):
        return self._databases

    @databases.setter
    def databases(self, value):
        if isinstance(value, list):
            for dbname in value:
                self._add_database(dbname)
        else:
            self._add_database(value)

    @property
    def host(self):
        if self._host is None:
            return self._HOSTNAME_WILDCARD
        return self._host

    @host.setter
    def host(self, value):
        self.check_string(value, "User host name")
        if self._is_valid_host_name(value):
            self._host = value
        else:
            raise ValueError(_("'%s' is not a valid hostname.") % value)

    def _build_database_schema(self, name):
        """Build a schema for this user.
        :type name:             string
        """
        return self.schema_model(name)

    def deserialize_schema(self, value):
        """Deserialize a user's databases value.
        :type value:            dict
        """
        return self.schema_model.deserialize(value)

    def _validate_user_name(self, value):
        """Perform validations on a given user name.
        :param value:        Validated user name.
        :type value:         string
        :raises:             ValueError On validation errors.
        """
        if not value:
            raise ValueError(_("User name empty."))
        self.check_string(value, "User name")
        if self._max_user_name_length and (len(value) >
                                           self._max_user_name_length):
            raise ValueError(_("User name '%(name)s' is too long. "
                               "Max length = %(max_length)d.")
                             % {'name': value,
                                'max_length': self._max_user_name_length})
        elif not self._is_valid_user_name(value):
            raise ValueError(_("'%s' is not a valid user name.") % value)

    @property
    def _max_user_name_length(self):
        """Return the maximum valid user name length if any.
        :returns:            Maximum user name length or None if unlimited.
        """
        return None

    def _is_valid_user_name(self, value):
        """Validate a given user name.
        :param value:        User name to be validated.
        :type value:         string
        :returns:            TRUE if valid, FALSE otherwise.
        """
        return True

    def _is_valid_host_name(self, value):
        """Validate a given host name.
        :param value:        Host name to be validated.
        :type value:         string
        :returns:            TRUE if valid, FALSE otherwise.
        """
        return True

    def _is_valid_password(self, value):
        """Validate a given password.
        :param value:        Password to be validated.
        :type value:         string
        :returns:            TRUE if valid, FALSE otherwise.
        """
        return True

    def _is_valid_database(self, value):
        """Validate a given database (serialized schema object).
        :param value:        The database to be validated.
        :type value:         dict
        :returns:            TRUE if valid, FALSE otherwise.
        :raises:             ValueError if operation not allowed.
        """
        return value not in self.databases

    def verify_dict(self):
        """Check that the object's dictionary values are valid by reloading
        them via the property setters. The checkers should raise the
        ValueError exception if invalid. All mandatory fields should be
        checked.
        """
        self.name = self._name
        if self.__dict__.get('_password'):
            self.password = self._password
        else:
            self._password = None
        if self.__dict__.get('_host'):
            self.host = self._host
        else:
            self._host = self._HOSTNAME_WILDCARD
        if self.__dict__.get('_databases'):
            for database in self._databases:
                # Create the schema for validation only
                self.deserialize_schema(database)
        else:
            self._databases = []
        if not self.__dict__.get('_is_root'):
            self._is_root = False

    @property
    def schema_model(self):
        return DatastoreSchema

    @property
    def ignored_users(self):
        if self._is_root:
            return []
        return cfg.get_ignored_users()

    @property
    def is_ignored(self):
        return self.name in self.ignored_users

    def make_root(self):
        self._is_root = True

    def check_reserved(self):
        """Check if the name is on the ignore_users list, meaning it is
        reserved.
        :raises:             ValueError if name is on the reserved list.
        """
        if self.is_ignored:
            raise ValueError(_('User name "%(name)s" is on the reserved '
                               'list: %(reserved)s.')
                             % {'name': self.name,
                                'reserved': self.ignored_users})

    def _create_checks(self):
        """Checks to be performed before user can be created."""
        self.check_reserved()

    def check_create(self):
        """Check if the user can be created.
        :raises:             ValueError if the user is not valid for create.
        """
        try:
            self._create_checks()
        except ValueError as e:
            raise ValueError(_('Cannot create user: %(error)s')
                             % {'error': str(e)})

    def _delete_checks(self):
        """Checks to be performed before user can be created."""
        self.check_reserved()

    def check_delete(self):
        """Check if the user can be deleted.
        :raises:             ValueError if the user is not valid for delete.
        """
        try:
            self._delete_checks()
        except ValueError as e:
            raise ValueError(_('Cannot delete user: %(error)s')
                             % {'error': str(e)})