summaryrefslogtreecommitdiff
path: root/trove/configuration/service.py
blob: 485e6e17b24573500b7929bfd5b13bf8c93c848c (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
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
# Copyright 2014 Rackspace
# 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.

from datetime import datetime

from oslo_log import log as logging
import six

import trove.common.apischema as apischema
from trove.common import cfg
from trove.common import exception
from trove.common.i18n import _
from trove.common import notification
from trove.common.notification import StartNotification, EndNotification
from trove.common import pagination
from trove.common import policy
from trove.common import wsgi
from trove.configuration import models
from trove.configuration.models import DBConfigurationParameter
from trove.configuration import views
from trove.datastore import models as ds_models
from trove.instance import models as instances_models


CONF = cfg.CONF
LOG = logging.getLogger(__name__)


class ConfigurationsController(wsgi.Controller):

    schemas = apischema.configuration

    @classmethod
    def authorize_config_action(cls, context, config_rule_name, config):
        policy.authorize_on_target(
            context, 'configuration:%s' % config_rule_name,
            {'tenant': config.tenant_id})

    def index(self, req, tenant_id):
        context = req.environ[wsgi.CONTEXT_KEY]
        configs, marker = models.Configurations.load(context)
        policy.authorize_on_tenant(context, 'configuration:index')
        view = views.ConfigurationsView(configs)
        paged = pagination.SimplePaginatedDataView(req.url, 'configurations',
                                                   view, marker)
        return wsgi.Result(paged.data(), 200)

    def show(self, req, tenant_id, id):
        LOG.debug("Showing configuration group %(id)s on tenant %(tenant)s"
                  % {"tenant": tenant_id, "id": id})
        context = req.environ[wsgi.CONTEXT_KEY]
        configuration = models.Configuration.load(context, id)
        self.authorize_config_action(context, 'show', configuration)
        configuration_items = models.Configuration.load_items(context, id)

        configuration.instance_count = instances_models.DBInstance.find_all(
            tenant_id=context.tenant,
            configuration_id=configuration.id,
            deleted=False).count()

        return wsgi.Result(views.DetailedConfigurationView(
                           configuration,
                           configuration_items).data(), 200)

    def instances(self, req, tenant_id, id):
        context = req.environ[wsgi.CONTEXT_KEY]
        configuration = models.Configuration.load(context, id)
        self.authorize_config_action(context, 'instances', configuration)
        instances = instances_models.DBInstance.find_all(
            tenant_id=context.tenant,
            configuration_id=configuration.id,
            deleted=False)
        limit = int(context.limit or CONF.instances_page_size)
        if limit > CONF.instances_page_size:
            limit = CONF.instances_page_size
        data_view = instances_models.DBInstance.find_by_pagination(
            'instances', instances, "foo",
            limit=limit,
            marker=context.marker)
        view = views.DetailedConfigurationInstancesView(data_view.collection)
        paged = pagination.SimplePaginatedDataView(req.url, 'instances', view,
                                                   data_view.next_page_marker)
        return wsgi.Result(paged.data(), 200)

    def create(self, req, body, tenant_id):
        LOG.debug("req : '%s'\n\n" % req)
        LOG.debug("body : '%s'\n\n" % req)

        context = req.environ[wsgi.CONTEXT_KEY]
        policy.authorize_on_tenant(context, 'configuration:create')
        context.notification = notification.DBaaSConfigurationCreate(
            context, request=req)
        name = body['configuration']['name']
        description = body['configuration'].get('description')
        values = body['configuration']['values']

        msg = _("Creating configuration group on tenant "
                "%(tenant_id)s with name: %(cfg_name)s")
        LOG.info(msg % {"tenant_id": tenant_id, "cfg_name": name})

        datastore_args = body['configuration'].get('datastore', {})
        datastore, datastore_version = (
            ds_models.get_datastore_version(**datastore_args))

        with StartNotification(context, name=name, datastore=datastore.name,
                               datastore_version=datastore_version.name):
            configItems = []
            if values:
                # validate that the values passed in are permitted by the
                # operator.
                ConfigurationsController._validate_configuration(
                    body['configuration']['values'],
                    datastore_version,
                    models.DatastoreConfigurationParameters.load_parameters(
                        datastore_version.id))

                for k, v in values.items():
                    configItems.append(DBConfigurationParameter(
                        configuration_key=k,
                        configuration_value=v))

            cfg_group = models.Configuration.create(name, description,
                                                    tenant_id, datastore.id,
                                                    datastore_version.id)
            with EndNotification(context, configuration_id=cfg_group.id):
                cfg_group_items = models.Configuration.create_items(
                    cfg_group.id, values)

        view_data = views.DetailedConfigurationView(cfg_group,
                                                    cfg_group_items)
        return wsgi.Result(view_data.data(), 200)

    def delete(self, req, tenant_id, id):
        msg = _("Deleting configuration group %(cfg_id)s on tenant: "
                "%(tenant_id)s")
        LOG.info(msg % {"tenant_id": tenant_id, "cfg_id": id})

        context = req.environ[wsgi.CONTEXT_KEY]
        group = models.Configuration.load(context, id)
        self.authorize_config_action(context, 'delete', group)
        context.notification = notification.DBaaSConfigurationDelete(
            context, request=req)
        with StartNotification(context, configuration_id=id):
            instances = instances_models.DBInstance.find_all(
                tenant_id=context.tenant,
                configuration_id=id,
                deleted=False).all()
            if instances:
                raise exception.InstanceAssignedToConfiguration()
            models.Configuration.delete(context, group)
        return wsgi.Result(None, 202)

    def update(self, req, body, tenant_id, id):
        msg = _("Updating configuration group %(cfg_id)s for tenant "
                "id %(tenant_id)s")
        LOG.info(msg % {"tenant_id": tenant_id, "cfg_id": id})

        context = req.environ[wsgi.CONTEXT_KEY]
        group = models.Configuration.load(context, id)
        # Note that changing the configuration group will also
        # indirectly affect all the instances which attach it.
        #
        # The Trove instance itself won't be changed (the same group is still
        # attached) but the configuration values will.
        #
        # The operator needs to keep this in mind when defining the related
        # policies.
        self.authorize_config_action(context, 'update', group)

        # if name/description are provided in the request body, update the
        # model with these values as well.
        if 'name' in body['configuration']:
            group.name = body['configuration']['name']

        if 'description' in body['configuration']:
            group.description = body['configuration']['description']

        context.notification = notification.DBaaSConfigurationUpdate(
            context, request=req)
        with StartNotification(context, configuration_id=id,
                               name=group.name, description=group.description):
            items = self._configuration_items_list(group,
                                                   body['configuration'])
            deleted_at = datetime.utcnow()
            models.Configuration.remove_all_items(context, group.id,
                                                  deleted_at)
            models.Configuration.save(group, items)
            self._refresh_on_all_instances(context, id)
        return wsgi.Result(None, 202)

    def edit(self, req, body, tenant_id, id):
        context = req.environ[wsgi.CONTEXT_KEY]
        group = models.Configuration.load(context, id)
        self.authorize_config_action(context, 'edit', group)
        context.notification = notification.DBaaSConfigurationEdit(
            context, request=req)
        with StartNotification(context, configuration_id=id):
            items = self._configuration_items_list(group,
                                                   body['configuration'])
            models.Configuration.save(group, items)
            self._refresh_on_all_instances(context, id)

    def _refresh_on_all_instances(self, context, configuration_id):
        """Refresh a configuration group on all its instances.
        """
        dbinstances = instances_models.DBInstance.find_all(
            tenant_id=context.tenant,
            configuration_id=configuration_id,
            deleted=False).all()

        LOG.debug(
            "All instances with configuration group '%s' on tenant '%s': %s"
            % (configuration_id, context.tenant, dbinstances))

        config = models.Configuration(context, configuration_id)
        for dbinstance in dbinstances:
            LOG.debug("Applying configuration group '%s' to instance: %s"
                      % (configuration_id, dbinstance.id))
            instance = instances_models.Instance.load(context, dbinstance.id)
            instance.update_overrides(config)

    def _configuration_items_list(self, group, configuration):
        ds_version_id = group.datastore_version_id
        ds_version = ds_models.DatastoreVersion.load_by_uuid(ds_version_id)
        items = []
        if 'values' in configuration:
            # validate that the values passed in are permitted by the operator.
            ConfigurationsController._validate_configuration(
                configuration['values'],
                ds_version,
                models.DatastoreConfigurationParameters.load_parameters(
                    ds_version.id))
            for k, v in configuration['values'].items():
                items.append(DBConfigurationParameter(
                    configuration_id=group.id,
                    configuration_key=k,
                    configuration_value=v,
                    deleted=False))
        return items

    @staticmethod
    def _validate_configuration(values, datastore_version, config_rules):
        LOG.info(_("Validating configuration values"))

        # create rules dictionary based on parameter name
        rules_lookup = {}
        for item in config_rules:
            rules_lookup[item.name.lower()] = item

        # checking if there are any rules for the datastore
        if not rules_lookup:
            output = {"version": datastore_version.name,
                      "name": datastore_version.datastore_name}
            msg = _("Configuration groups are not supported for this "
                    "datastore: %(name)s %(version)s") % output
            raise exception.UnprocessableEntity(message=msg)

        for k, v in values.items():
            key = k.lower()
            # parameter name validation
            if key not in rules_lookup:
                output = {"key": k,
                          "version": datastore_version.name,
                          "name": datastore_version.datastore_name}
                msg = _("The configuration parameter %(key)s is not "
                        "supported for this datastore: "
                        "%(name)s %(version)s.") % output
                raise exception.UnprocessableEntity(message=msg)

            rule = rules_lookup[key]

            # type checking
            value_type = rule.data_type

            if not isinstance(v, ConfigurationsController._find_type(
                    value_type)):
                output = {"key": k, "type": value_type}
                msg = _("The value provided for the configuration "
                        "parameter %(key)s is not of type %(type)s.") % output
                raise exception.UnprocessableEntity(message=msg)

            # integer min/max checking
            if isinstance(v, six.integer_types) and not isinstance(v, bool):
                if rule.min_size is not None:
                    try:
                        min_value = int(rule.min_size)
                    except ValueError:
                        raise exception.TroveError(_(
                            "Invalid or unsupported min value defined in the "
                            "configuration-parameters configuration file. "
                            "Expected integer."))
                    if v < min_value:
                        output = {"key": k, "min": min_value}
                        message = _(
                            "The value for the configuration parameter "
                            "%(key)s is less than the minimum allowed: "
                            "%(min)s") % output
                        raise exception.UnprocessableEntity(message=message)

                if rule.max_size is not None:
                    try:
                        max_value = int(rule.max_size)
                    except ValueError:
                        raise exception.TroveError(_(
                            "Invalid or unsupported max value defined in the "
                            "configuration-parameters configuration file. "
                            "Expected integer."))
                    if v > max_value:
                        output = {"key": k, "max": max_value}
                        message = _(
                            "The value for the configuration parameter "
                            "%(key)s is greater than the maximum "
                            "allowed: %(max)s") % output
                        raise exception.UnprocessableEntity(message=message)

    @staticmethod
    def _find_type(value_type):
        if value_type == "boolean":
            return bool
        elif value_type == "string":
            return six.string_types
        elif value_type == "integer":
            return six.integer_types
        elif value_type == "float":
            return float
        else:
            raise exception.TroveError(_(
                "Invalid or unsupported type defined in the "
                "configuration-parameters configuration file."))

    @staticmethod
    def _get_item(key, dictList):
        for item in dictList:
            if key == item.get('name'):
                return item
        raise exception.UnprocessableEntity(
            message=_("%s is not a supported configuration parameter.") % key)


class ParametersController(wsgi.Controller):

    @classmethod
    def authorize_request(cls, req, rule_name):
        """Parameters (configuration templates) bind to a datastore.
        Datastores are not owned by any particular tenant so we only check
        the current tenant is allowed to perform the action.
        """
        context = req.environ[wsgi.CONTEXT_KEY]
        policy.authorize_on_tenant(context, 'configuration-parameter:%s'
                                   % rule_name)

    def index(self, req, tenant_id, datastore, id):
        self.authorize_request(req, 'index')
        ds, ds_version = ds_models.get_datastore_version(
            type=datastore, version=id)
        rules = models.DatastoreConfigurationParameters.load_parameters(
            ds_version.id)
        return wsgi.Result(views.ConfigurationParametersView(rules).data(),
                           200)

    def show(self, req, tenant_id, datastore, id, name):
        self.authorize_request(req, 'show')
        ds, ds_version = ds_models.get_datastore_version(
            type=datastore, version=id)
        rule = models.DatastoreConfigurationParameters.load_parameter_by_name(
            ds_version.id, name)
        return wsgi.Result(views.ConfigurationParameterView(rule).data(), 200)

    def index_by_version(self, req, tenant_id, version):
        self.authorize_request(req, 'index_by_version')
        ds_version = ds_models.DatastoreVersion.load_by_uuid(version)
        rules = models.DatastoreConfigurationParameters.load_parameters(
            ds_version.id)
        return wsgi.Result(views.ConfigurationParametersView(rules).data(),
                           200)

    def show_by_version(self, req, tenant_id, version, name):
        self.authorize_request(req, 'show_by_version')
        ds_models.DatastoreVersion.load_by_uuid(version)
        rule = models.DatastoreConfigurationParameters.load_parameter_by_name(
            version, name)
        return wsgi.Result(views.ConfigurationParameterView(rule).data(), 200)