Debian Codegraph @

cloudkitty_tempest_plugin/services/client.py

raw
1 # -*- coding: utf-8 -*-
2 # Copyright 2017 Objectif Libre
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15 #
16
17 from keystoneauth1.identity import v3
18 from keystoneauth1 import session
19 from keystoneclient import client
20 from oslo_serialization import jsonutils as json
21 from tempest import clients as tempest_clients
22 from tempest import config
23 from tempest.lib.common import rest_client
24 from tempest.lib.services import clients
25
26 CONF = config.CONF
27
28
29 class BaseRatingClient(rest_client.RestClient):
30 """Base class for cloudkittyclient implementations"""
31
32 @staticmethod
33 def deserialize(body):
34 return json.loads(body.decode().replace("\n", ""))
35
36 @staticmethod
37 def serialize(body):
38 return json.dumps(body)
39
40 def _do_request(self, method, uri, body=None, expected_code=200):
41 resp, body = self.request(method, uri, body=body)
42 self.expected_success(expected_code, resp.status)
43 body = self.deserialize(body) if body else dict()
44 if not isinstance(body, dict) and not isinstance(body, list):
45 body = dict()
46 # ResponseBody inherits from dict, so lists must be converted
47 body = dict(body=body) if isinstance(body, list) else body
48 return rest_client.ResponseBody(resp, body)
49
50
51 class RatingClientV1(BaseRatingClient):
52 """Implementation of cloudkittyclient for v1 endpoints"""
53
54 api_version = 'v1'
55
56 def get_collector_mappings(self, service=None):
57 uri = '/collector/mappings/'
58 if service:
59 uri += service + '/'
60 return self._do_request('GET', uri)
61
62 def create_collector_mapping(self, collector='gnocchi', service='compute'):
63 uri = '/collector/mappings/'
64 request_body = {
65 'collector': collector,
66 'service': service,
67 }
68 return self._do_request('POST', uri, body=self.serialize(request_body))
69
70 def delete_collector_mapping(self, service='compute'):
71 uri = '/collector/mappings'
72 request_body = {
73 'service': service,
74 }
75 return self._do_request('DELETE', uri,
76 body=self.serialize(request_body),
77 expected_code=204)
78
79 def get_collector_state(self, collector="gnocchi"):
80 uri = '/collector/states/'
81 request_body = {
82 'name': collector,
83 }
84 return self._do_request('GET', uri, body=self.serialize(request_body))
85
86 def set_collector_state(self, collector="gnocchi", enabled=True):
87 uri = '/collector/states/'
88 request_body = {
89 'name': collector,
90 'enabled': enabled,
91 }
92 return self._do_request('PUT', uri, body=self.serialize(request_body))
93
94 def get_config(self):
95 uri = '/info/config/'
96 return self._do_request('GET', uri)
97
98 def get_metric(self, metric_name=None):
99 uri = '/info/metrics/'
100 if metric_name:
101 uri += metric_name + '/'
102 return self._do_request('GET', uri)
103
104 def get_rating_module(self, module_name=None):
105 uri = '/rating/modules/'
106 if module_name:
107 uri += module_name + '/'
108 return self._do_request('GET', uri)
109
110 def update_rating_module(self, module_name, description='',
111 enabled=False, hot_config=True, priority=1):
112 uri = '/rating/modules/' + module_name + '/'
113 request_body = {
114 'module_id': module_name,
115 'description': description,
116 'enabled': enabled,
117 'hot-config': hot_config,
118 'priority': priority,
119 }
120 return self._do_request('PUT', uri, body=self.serialize(request_body),
121 expected_code=302)
122
123 def reload_rating_modules(self):
124 uri = '/rating/reload_modules'
125 return self._do_request('GET', uri, expected_code=204)
126
127 def get_report_summary(self):
128 uri = '/report/summary/'
129 return self._do_request('GET', uri)
130
131 def get_rated_tenants(self):
132 uri = '/report/tenants/'
133 return self._do_request('GET', uri)
134
135 def get_report_total(self):
136 uri = '/report/total/'
137 return self._do_request('GET', uri)
138
139 def get_storage_dataframes(self):
140 uri = '/storage/dataframes/'
141 return self._do_request('GET', uri)
142
143 def get_hashmap_mapping_types(self):
144 uri = '/rating/module_config/hashmap/types/'
145 return self._do_request('GET', uri)
146
147 def get_hashmap_service(self, service_id=None):
148 uri = '/rating/module_config/hashmap/services/'
149 if service_id:
150 uri += service_id + '/'
151 return self._do_request('GET', uri)
152
153 def create_hashmap_service(self, name, service_id=None):
154 uri = '/rating/module_config/hashmap/services/'
155 request_body = {
156 'name': name,
157 }
158 if service_id:
159 request_body['service_id'] = service_id
160 return self._do_request('POST', uri,
161 body=self.serialize(request_body),
162 expected_code=201)
163
164 def delete_hashmap_service(self, service_id):
165 uri = '/rating/module_config/hashmap/services/'
166 request_body = {
167 'service_id': service_id,
168 }
169 return self._do_request('DELETE', uri,
170 body=self.serialize(request_body),
171 expected_code=204)
172
173 def get_hashmap_fields(self, service_id):
174 uri = '/rating/module_config/hashmap/fields/'
175 request_body = {
176 'service_id': service_id,
177 }
178 return self._do_request('GET', uri,
179 body=self.serialize(request_body))
180
181 def get_hashmap_field(self, field_id):
182 uri = '/rating/module_config/hashmap/fields/' + field_id + '/'
183 return self._do_request('GET', uri)
184
185 def create_hashmap_field(self, field_name, service_id, field_id=None):
186 uri = '/rating/module_config/hashmap/fields/'
187 request_body = {
188 'name': field_name,
189 'service_id': service_id,
190 }
191 if field_id:
192 request_body['field_id'] = field_id
193 return self._do_request('POST', uri,
194 body=self.serialize(request_body),
195 expected_code=201)
196
197 def delete_hashmap_field(self, field_id):
198 uri = '/rating/module_config/hashmap/fields/'
199 request_body = {
200 'field_id': field_id,
201 }
202 return self._do_request('DELETE', uri,
203 body=self.serialize(request_body),
204 expected_code=204)
205
206 def get_hashmap_mappings(self, service_id=None, field_id=None,
207 group_id=None, no_group=False, tenant_id=None,
208 filter_tenant=False):
209 args = locals()
210 args.pop('self')
211 uri = '/rating/module_config/hashmap/mappings/'
212 request_body = dict((k, v)
213 for k, v in args.items() if v is not None)
214 return self._do_request('GET', uri,
215 body=self.serialize(request_body))
216
217 def get_hashmap_mapping(self, mapping_id):
218 uri = '/rating/module_config/hashmap/mappings/' + mapping_id + '/'
219 return self._do_request('GET', uri)
220
221 def create_hashmap_mapping(self, cost=0, field_id=None, group_id=None,
222 map_type=None, mapping_id=None, service_id=None,
223 tenant_id=None, value=None):
224 args = locals()
225 args.pop('self')
226 uri = '/rating/module_config/hashmap/mappings/'
227 request_body = dict((k, v)
228 for k, v in args.items() if v is not None)
229 return self._do_request('POST', uri,
230 body=self.serialize(request_body),
231 expected_code=201)
232
233 def delete_hashmap_mapping(self, mapping_id):
234 uri = '/rating/module_config/hashmap/mappings/'
235 request_body = {
236 'mapping_id': mapping_id,
237 }
238 return self._do_request('DELETE', uri,
239 body=self.serialize(request_body),
240 expected_code=204)
241
242 def update_hashmap_mapping(self, mapping_id, cost=0,
243 field_id=None, group_id=None, map_type=None,
244 service_id=None, tenant_id=None, value=None,
245 end=None):
246 args = locals()
247 args.pop('self')
248 uri = '/rating/module_config/hashmap/mappings/'
249 request_body = dict((k, v)
250 for k, v in args.items() if v is not None)
251 return self._do_request('PUT', uri,
252 body=self.serialize(request_body),
253 expected_code=302)
254
255 def get_hashmap_mapping_group(self, mapping_id):
256 uri = '/rating/module_config/hashmap/mappings/group/'
257 request_body = {
258 'mapping_id': mapping_id,
259 }
260 return self._do_request('GET', uri,
261 body=self.serialize(request_body))
262
263 def get_hashmap_group(self, group_id=None):
264 uri = '/rating/module_config/hashmap/groups/'
265 if group_id:
266 uri += group_id + '/'
267 return self._do_request('GET', uri)
268
269 def create_hashmap_group(self, group_name, group_id=None):
270 uri = '/rating/module_config/hashmap/groups'
271 request_body = {
272 'name': group_name,
273 }
274 if group_id:
275 request_body['group_id'] = group_id
276 return self._do_request('POST', uri,
277 body=self.serialize(request_body),
278 expected_code=201)
279
280 def delete_hashmap_group(self, group_id):
281 uri = '/rating/module_config/hashmap/groups'
282 request_body = {
283 'group_id': group_id,
284 }
285 return self._do_request('DELETE', uri,
286 body=self.serialize(request_body),
287 expected_code=204)
288
289 def get_hashmap_group_mappings(self, group_id):
290 uri = '/rating/module_config/hashmap/groups/mappings/'
291 request_body = {
292 'group_id': group_id,
293 }
294 return self._do_request('GET', uri,
295 body=self.serialize(request_body))
296
297 def get_hashmap_group_threshold(self, group_id):
298 uri = '/rating/module_config/hashmap/groups/thresholds/'
299 request_body = {
300 'group_id': group_id,
301 }
302 return self._do_request('GET', uri,
303 body=self.serialize(request_body))
304
305 def get_hashmap_threshold(self, threshold_id):
306 uri = '/rating/module_config/hashmap/thresholds/' + threshold_id + '/'
307 return self._do_request('GET', uri)
308
309 def get_hashmap_thresholds(self, service_id=None,
310 field_id=None, group_id=None):
311 args = locals()
312 args.pop('self')
313 uri = '/rating/module_config/hashmap/thresholds/'
314 request_body = dict((k, v)
315 for k, v in args.items() if v is not None)
316 return self._do_request('GET', uri,
317 body=self.serialize(request_body))
318
319 def create_hashmap_threshold(self, field_id=None, group_id=None,
320 threshold_id=None, map_type=None, cost=None,
321 service_id=None, tenant_id=None, level=None):
322 args = locals()
323 args.pop('self')
324 uri = '/rating/module_config/hashmap/thresholds/'
325 request_body = dict((k, v)
326 for k, v in args.items() if v is not None)
327 return self._do_request('POST', uri,
328 body=self.serialize(request_body),
329 expected_code=201)
330
331 def update_hashmap_threshold(self, threshold_id, field_id=None,
332 group_id=None, map_type=None, cost=None,
333 service_id=None, tenant_id=None, level=None):
334 args = locals()
335 args.pop('self')
336 uri = '/rating/module_config/hashmap/thresholds/'
337 request_body = dict((k, v)
338 for k, v in args.items() if v is not None)
339 return self._do_request('PUT', uri,
340 body=self.serialize(request_body),
341 expected_code=302)
342
343 def delete_hashmap_threshold(self, threshold_id):
344 uri = '/rating/module_config/hashmap/thresholds/'
345 request_body = {
346 'threshold_id': threshold_id,
347 }
348 return self._do_request('DELETE', uri,
349 body=self.serialize(request_body),
350 expected_code=204)
351
352 def get_pyscripts(self, no_data=False):
353 uri = '/rating/module_config/pyscripts/scripts/'
354 request_body = {
355 'no_data': no_data,
356 }
357 return self._do_request('GET', uri, body=self.serialize(request_body))
358
359 def get_pyscript(self, script_id):
360 uri = '/rating/module_config/pyscripts/scripts/' + script_id + '/'
361 return self._do_request('GET', uri)
362
363 @staticmethod
364 def _get_pyscript_request_body(name, data, checksum, script_id, end=None):
365 args = locals()
366 request_body = dict((k, v)
367 for k, v in args.items() if v is not None)
368 return request_body
369
370 def create_pyscript(self, name, data, checksum=None, script_id=None):
371 uri = '/rating/module_config/pyscripts/scripts/'
372 request_body = self._get_pyscript_request_body(name, data,
373 checksum, script_id)
374 return self._do_request('POST', uri,
375 body=self.serialize(request_body),
376 expected_code=201)
377
378 def update_pyscript(self, script_id, name=None, data=None, checksum=None,
379 end=None):
380 uri = '/rating/module_config/pyscripts/scripts/'
381 request_body = self._get_pyscript_request_body(name, data,
382 checksum, script_id,
383 end)
384 return self._do_request('PUT', uri,
385 body=self.serialize(request_body),
386 expected_code=201)
387
388 def delete_pyscript(self, script_id):
389 uri = '/rating/module_config/pyscripts/scripts/'
390 request_body = {
391 'script_id': script_id,
392 }
393 return self._do_request('DELETE', uri,
394 body=self.serialize(request_body),
395 expected_code=204)
396
397
398 class RatingClientV2(RatingClientV1):
399 """Implementation of cloudkittyclient for v2 endpoints"""
400
401 api_version = 'v2'
402
403
404 class CustomIdentityClient(object):
405 """Custom Keystone client
406
407 Class used by the CK tempest plugin to add the 'rating' role to
408 the dynamically allocated test tenant
409 """
410
411 def __init__(self):
412 self.admin_auth = v3.Password(
413 auth_url=CONF.identity.uri_v3,
414 username=CONF.auth.admin_username,
415 password=CONF.auth.admin_password,
416 project_name=CONF.auth.admin_project_name,
417 project_domain_name=CONF.auth.admin_domain_name,
418 user_domain_name=CONF.auth.admin_domain_name,
419 )
420 self.admin_session = session.Session(auth=self.admin_auth)
421 self.admin_client = client.Client(session=self.admin_session)
422 self.ck_user_id = self._get_ck_user_id()
423 self.rating_role_id = self._get_rating_role_id()
424
425 def enable_rating(self, project_id):
426 """Assigns the 'rating' role to ck user on the given project"""
427 self.admin_client.roles.grant(self.rating_role_id,
428 user=self.ck_user_id,
429 project=project_id)
430
431 @staticmethod
432 def _find_item(iterable, key, value):
433 item = None
434 for elem in iterable:
435 if getattr(elem, key, None) == value:
436 item = elem
437 return item
438
439 def _get_ck_user_id(self):
440 users = self.admin_client.users.list()
441 return getattr(
442 self._find_item(users, 'name', CONF.rating_plugin.user_name),
443 'id', None,
444 )
445
446 def _get_rating_role_id(self):
447 roles = self.admin_client.roles.list()
448 return getattr(
449 self._find_item(roles, 'name', 'rating'), 'id', None,
450 )
451
452
453 class Manager(clients.ServiceClients):
454 rating_params = {
455 'service': CONF.rating_plugin.service_name,
456 'region': CONF.identity.region,
457 'endpoint_type': CONF.rating_plugin.endpoint_type,
458 }
459
460 def __init__(self, credentials=None, service=None):
461 dscv = CONF.identity.disable_ssl_certificate_validation
462 _, uri = tempest_clients.get_auth_provider_class(credentials)
463 super(Manager, self).__init__(
464 credentials=credentials,
465 identity_uri=uri,
466 scope='project',
467 disable_ssl_certificate_validation=dscv,
468 ca_certs=CONF.identity.ca_certificates_file,
469 trace_requests=CONF.debug.trace_requests)
470 self.rating_clients = {
471 'v1': RatingClientV1(self.auth_provider, **self.rating_params),
472 'v2': RatingClientV2(self.auth_provider, **self.rating_params),
473 }
474
475 def get_rating_client(self, api_version='v2'):
476 if api_version not in self.rating_clients:
477 raise ValueError('API version must be one of the following: {}',
478 list(self.rating_client.keys()))
479 return self.rating_clients[api_version]