File: api_versions.py

package info (click to toggle)
rally-openstack 3.0.0-8
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 8,928 kB
  • sloc: python: 53,131; sh: 262; makefile: 38
file content (275 lines) | stat: -rw-r--r-- 10,396 bytes parent folder | download | duplicates (4)
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
#    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 random

from rally.common import validation
from rally import exceptions

from rally_openstack.common import consts
from rally_openstack.common import osclients
from rally_openstack.task import context


@validation.configure("check_api_versions")
class CheckOpenStackAPIVersionsValidator(validation.Validator):
    """Additional validation for api_versions context"""

    def validate(self, context, config, plugin_cls, plugin_cfg):
        for client in plugin_cfg:
            client_cls = osclients.OSClient.get(client)
            try:
                if ("service_type" in plugin_cfg[client]
                        or "service_name" in plugin_cfg[client]):
                    client_cls.is_service_type_configurable()

                if "version" in plugin_cfg[client]:
                    client_cls.validate_version(plugin_cfg[client]["version"])

            except exceptions.RallyException as e:
                return self.fail(
                    "Invalid settings for '%(client)s': %(error)s" % {
                        "client": client,
                        "error": e.format_message()})


@validation.add("check_api_versions")
@context.configure(name="api_versions", platform="openstack", order=150)
class OpenStackAPIVersions(context.OpenStackContext):
    """Context for specifying OpenStack clients versions and service types.

    Some OpenStack services support several API versions. To recognize
    the endpoints of each version, separate service types are provided in
    Keystone service catalog.

    Rally has the map of default service names - service types. But since
    service type is an entity, which can be configured manually by admin(
    via keystone api) without relation to service name, such map can be
    insufficient.

    Also, Keystone service catalog does not provide a map types to name
    (this statement is true for keystone < 3.3 ).

    This context was designed for not-default service types and not-default
    API versions usage.

    An example of specifying API version:

    .. code-block:: json

        # In this example we will launch NovaKeypair.create_and_list_keypairs
        # scenario on 2.2 api version.
        {
            "NovaKeypair.create_and_list_keypairs": [
                {
                    "args": {
                        "key_type": "x509"
                    },
                    "runner": {
                        "type": "constant",
                        "times": 10,
                        "concurrency": 2
                    },
                    "context": {
                        "users": {
                            "tenants": 3,
                            "users_per_tenant": 2
                        },
                        "api_versions": {
                            "nova": {
                                "version": 2.2
                            }
                        }
                    }
                }
            ]
        }

    An example of specifying API version along with service type:

    .. code-block:: json

        # In this example we will launch CinderVolumes.create_and_attach_volume
        # scenario on Cinder V2
        {
            "CinderVolumes.create_and_attach_volume": [
                {
                    "args": {
                        "size": 10,
                        "image": {
                            "name": "^cirros.*-disk$"
                        },
                        "flavor": {
                            "name": "m1.tiny"
                        },
                        "create_volume_params": {
                            "availability_zone": "nova"
                        }
                    },
                    "runner": {
                        "type": "constant",
                        "times": 5,
                        "concurrency": 1
                    },
                    "context": {
                        "users": {
                            "tenants": 2,
                            "users_per_tenant": 2
                        },
                        "api_versions": {
                            "cinder": {
                                "version": 2,
                                "service_type": "volumev2"
                            }
                        }
                    }
                }
            ]
        }

    Also, it possible to use service name as an identifier of service endpoint,
    but an admin user is required (Keystone can return map of service
    names - types, but such API is permitted only for admin). An example:

    .. code-block:: json

        # Similar to the previous example, but `service_name` argument is used
        # instead of `service_type`
        {
            "CinderVolumes.create_and_attach_volume": [
                {
                    "args": {
                        "size": 10,
                        "image": {
                            "name": "^cirros.*-disk$"
                        },
                        "flavor": {
                            "name": "m1.tiny"
                        },
                        "create_volume_params": {
                            "availability_zone": "nova"
                        }
                    },
                    "runner": {
                        "type": "constant",
                        "times": 5,
                        "concurrency": 1
                    },
                    "context": {
                        "users": {
                            "tenants": 2,
                            "users_per_tenant": 2
                        },
                        "api_versions": {
                            "cinder": {
                                "version": 2,
                                "service_name": "cinderv2"
                            }
                        }
                    }
                }
            ]
        }

    """
    VERSION_SCHEMA = {
        "anyOf": [
            {"type": "string", "description": "a string-like version."},
            {"type": "number", "description": "a number-like version."}
        ]
    }
    CONFIG_SCHEMA = {
        "type": "object",
        "$schema": consts.JSON_SCHEMA,
        "patternProperties": {
            "^[a-z]+$": {
                "type": "object",
                "oneOf": [
                    {
                        "description": "version only",
                        "properties": {
                            "version": VERSION_SCHEMA,
                        },
                        "required": ["version"],
                        "additionalProperties": False
                    },
                    {
                        "description": "version and service_name",
                        "properties": {
                            "version": VERSION_SCHEMA,
                            "service_name": {"type": "string"}
                        },
                        "required": ["service_name"],
                        "additionalProperties": False
                    },
                    {
                        "description": "version and service_type",
                        "properties": {
                            "version": VERSION_SCHEMA,
                            "service_type": {"type": "string"}
                        },
                        "required": ["service_type"],
                        "additionalProperties": False
                    }
                ],
            }
        },
        "minProperties": 1,
        "additionalProperties": False
    }

    def setup(self):
        # FIXME(andreykurilin): move all checks to validate method.

        # use admin only when `service_name` is presented
        admin_clients = osclients.Clients(
            self.context.get("admin", {}).get("credential"))
        clients = osclients.Clients(random.choice(
            self.context["users"])["credential"])
        services = clients.keystone.service_catalog.get_endpoints()
        services_from_admin = None
        for client_name, conf in self.config.items():
            if "service_type" in conf and conf["service_type"] not in services:
                raise exceptions.ValidationError(
                    "There is no service with '%s' type in your environment."
                    % conf["service_type"])
            elif "service_name" in conf:
                if not self.context.get("admin", {}).get("credential"):
                    raise exceptions.ContextSetupFailure(
                        ctx_name=self.get_name(),
                        msg="Setting 'service_name' is admin only operation.")
                if not services_from_admin:
                    services_from_admin = dict(
                        [(s.name, s.type)
                         for s in admin_clients.keystone().services.list()])
                if conf["service_name"] not in services_from_admin:
                    raise exceptions.ValidationError(
                        "There is no '%s' service in your environment"
                        % conf["service_name"])

                # TODO(boris-42): Use separate key ["openstack"]["versions"]
                self.context["config"]["api_versions@openstack"][client_name][
                    "service_type"] = services_from_admin[conf["service_name"]]

        admin_cred = self.context.get("admin", {}).get("credential")
        if admin_cred:
            admin_cred["api_info"].update(
                self.context["config"]["api_versions@openstack"]
            )
        for user in self.context["users"]:
            user["credential"]["api_info"].update(
                self.context["config"]["api_versions@openstack"]
            )

    def cleanup(self):
        # nothing to do here
        pass