Debian Codegraph @

neutron_lib/placement/client.py

raw
1 # Copyright (c) 2016 IBM
2 # All Rights Reserved.
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 import functools
17 import re
18 import time
19 from urllib import parse
20 import uuid as uuid_lib
21
22 import requests
23
24 from keystoneauth1 import exceptions as ks_exc
25 from keystoneauth1 import loading as keystone
26 from oslo_log import log as logging
27 from oslo_serialization import jsonutils
28 from oslo_utils import versionutils
29
30 from neutron_lib._i18n import _
31 from neutron_lib.exceptions import placement as n_exc
32
33
34 LOG = logging.getLogger(__name__)
35
36 API_VERSION_REQUEST_HEADER = 'OpenStack-API-Version'
37 PLACEMENT_API_WITH_MEMBER_OF = 'placement 1.3'
38 PLACEMENT_API_WITH_NESTED_RESOURCES = 'placement 1.14'
39 PLACEMENT_API_RETURN_PROVIDER_BODY = 'placement 1.20'
40 PLACEMENT_API_ERROR_CODE = 'placement 1.23'
41 PLACEMENT_API_CONSUMER_GENERATION = 'placement 1.28'
42 PLACEMENT_API_UPDATE_REPARENT = 'placement 1.37'
43 PLACEMENT_API_LATEST_SUPPORTED = PLACEMENT_API_UPDATE_REPARENT
44 GENERATION_CONFLICT_RETRIES = 10
45
46
47 def _check_placement_api_available(f):
48 """Check if the placement API is available.
49
50 :param f: Function to execute.
51 :returns: The returned value of the function f.
52 """
53 @functools.wraps(f)
54 def wrapper(self, *a, **k):
55 try:
56 if not self._client:
57 self._client = self._create_client()
58 return f(self, *a, **k)
59 except ks_exc.http.HttpError as exc:
60 if 400 <= exc.http_status <= 499:
61 # NOTE(bence romsics): Placement has inconsistently formatted
62 # error messages. Some error response bodies are JSON
63 # formatted, seemingly machine readible objects. While others
64 # are free format text. We have to keep the whole thing
65 # to avoid losing information.
66 raise n_exc.PlacementClientError(
67 msg=exc.response.text.replace('\n', ' '))
68 raise
69 return wrapper
70
71
72 def _get_version(openstack_api_version):
73 match = re.search(r"placement (?P<api_version>\d+\.\d+)",
74 openstack_api_version)
75 return versionutils.convert_version_to_tuple(match.group('api_version'))
76
77
78 class UUIDEncoder(jsonutils.JSONEncoder):
79 def default(self, o):
80 if isinstance(o, uuid_lib.UUID):
81 return str(o)
82 return super().default(o)
83
84
85 class NoAuthClient:
86 """Placement NoAuthClient for fullstack testing"""
87
88 def __init__(self, url):
89 self.url = url
90 # TODO(lajoskatona): use perhaps http_connect_timeout from
91 # keystone_authtoken group
92 self.timeout = 5
93 self.retries = 2
94
95 def request(self, url, method, body=None, headers=None, **kwargs):
96 headers = headers or {}
97 headers.setdefault('Accept', 'application/json')
98
99 # Note(lajoskatona): placement report plugin fills uuid fields with
100 # UUID objects, and that is good for keystone, but requests goes mad
101 # with that if we use json=body as it can't serialize UUID.
102 # To make things worse if we give a serialized json, it will do the
103 # jsonification again, so better to create the json here and give it
104 # to requests with the data parameter.
105 body = jsonutils.dumps(body, cls=UUIDEncoder)
106 for i in range(self.retries):
107 try:
108 resp = requests.request(
109 method,
110 url,
111 data=body,
112 headers=headers,
113 verify=False,
114 timeout=self.timeout,
115 **kwargs)
116 return resp
117 except requests.Timeout:
118 LOG.exception('requests Timeout, let\'s retry it...')
119 except requests.ConnectionError:
120 LOG.exception('Connection Error appeared')
121 except requests.RequestException:
122 LOG.exception('Some really weird thing happened, let\'s '
123 'retry it')
124 time.sleep(self.timeout)
125 # Note(lajoskatona): requests raise ConnectionError, but
126 # PlacementReportPlugin expects keystonauth1 HttpError.
127 raise ks_exc.HttpError
128
129 def get(self, url, endpoint_filter, **kwargs):
130 return self.request(f'{self.url}{url}', 'GET', **kwargs)
131
132 def post(self, url, json, endpoint_filter, **kwargs):
133 return self.request(f'{self.url}{url}', 'POST', body=json,
134 **kwargs)
135
136 def put(self, url, json, endpoint_filter, **kwargs):
137 resp = self.request(f'{self.url}{url}', 'PUT', body=json,
138 **kwargs)
139 return resp
140
141 def delete(self, url, endpoint_filter, **kwargs):
142 return self.request(f'{self.url}{url}', 'DELETE', **kwargs)
143
144
145 class PlacementAPIClient:
146 """Client class for placement ReST API."""
147
148 def __init__(self, conf,
149 openstack_api_version=PLACEMENT_API_LATEST_SUPPORTED):
150 self._openstack_api_version = openstack_api_version
151 self._target_version = _get_version(openstack_api_version)
152 self._conf = conf
153 self._ks_filter = {'service_type': 'placement',
154 'region_name': self._conf.placement.region_name,
155 'interface': self._conf.placement.endpoint_type}
156 self._api_version_header = {API_VERSION_REQUEST_HEADER:
157 self._openstack_api_version}
158 self._client = None
159
160 def _create_client(self):
161 """Create the HTTP session accessing the placement service."""
162 # Flush _resource_providers and aggregates so we start from a
163 # clean slate.
164 self._resource_providers = {}
165 self._provider_aggregate_map = {}
166 # TODO(lajoskatona): perhaps not the best to override config options,
167 # actually the abused keystoneauth1 options are:
168 # auth_type (used for deciding for NoAuthClient) and auth_section
169 # (used for communicating the url for the NoAuthClient)
170 if self._conf.placement.auth_type == 'noauth':
171 return NoAuthClient(self._conf.placement.auth_section)
172 else:
173 auth_plugin = keystone.load_auth_from_conf_options(
174 self._conf, 'placement')
175 return keystone.load_session_from_conf_options(
176 self._conf, 'placement', auth=auth_plugin,
177 additional_headers={'accept': 'application/json'})
178
179 def _extend_header_with_api_version(self, **kwargs):
180 headers = kwargs.get('headers', {})
181 if API_VERSION_REQUEST_HEADER not in headers:
182 if 'headers' not in kwargs:
183 kwargs['headers'] = self._api_version_header
184 else:
185 kwargs['headers'].update(self._api_version_header)
186 return kwargs
187
188 def _get(self, url, **kwargs):
189 kwargs = self._extend_header_with_api_version(**kwargs)
190 return self._client.get(url, endpoint_filter=self._ks_filter,
191 **kwargs)
192
193 def _post(self, url, data, **kwargs):
194 kwargs = self._extend_header_with_api_version(**kwargs)
195 return self._client.post(url, json=data,
196 endpoint_filter=self._ks_filter, **kwargs)
197
198 def _put(self, url, data, **kwargs):
199 kwargs = self._extend_header_with_api_version(**kwargs)
200 return self._client.put(url, json=data,
201 endpoint_filter=self._ks_filter, **kwargs)
202
203 def _put_with_retry_for_generation_conflict(
204 self, url, body,
205 resource_provider_uuid,
206 resource_provider_generation=None):
207
208 if resource_provider_generation is None:
209 # If the client's user did not supply a generation to us we dare to
210 # retry without handing the control back to our caller.
211 max_tries = GENERATION_CONFLICT_RETRIES
212 else:
213 # If the client's user supplied a generation to us we don't dare to
214 # retry on her behalf since we don't know her intention.
215 max_tries = 1
216
217 body['resource_provider_generation'] = resource_provider_generation
218
219 for i in range(max_tries):
220 if resource_provider_generation is None:
221 # In the bodies of
222 # PUT /resource_providers/{uuid}/traits
223 # PUT /resource_providers/{uuid}/inventories
224 # PUT /resource_providers/{uuid}/inventories/{resource_class}
225 # resource_provider_generation happens to be at the same place.
226 body['resource_provider_generation'] = \
227 self.get_resource_provider(
228 resource_provider_uuid=resource_provider_uuid)[
229 'generation']
230 try:
231 return self._put(url, body).json()
232 except ks_exc.Conflict as e:
233 if e.response.json()[
234 'errors'][0]['code'] == 'placement.concurrent_update':
235 continue
236 raise
237
238 raise n_exc.PlacementResourceProviderGenerationConflict(
239 resource_provider=resource_provider_uuid,
240 generation=body['resource_provider_generation'])
241
242 def _delete(self, url, **kwargs):
243 kwargs = self._extend_header_with_api_version(**kwargs)
244 return self._client.delete(url, endpoint_filter=self._ks_filter,
245 **kwargs)
246
247 @_check_placement_api_available
248 def create_resource_provider(self, resource_provider):
249 """Create a resource provider.
250
251 :param resource_provider: The resource provider. A dict with
252 the uuid (required),
253 the name (required) and
254 the parent_provider_uuid (optional).
255 :returns: The resource provider created.
256 """
257 url = '/resource_providers'
258 rsp = self._post(url, resource_provider)
259 if (self._target_version <
260 _get_version(PLACEMENT_API_RETURN_PROVIDER_BODY)):
261 return
262 else:
263 return rsp.json()
264
265 @_check_placement_api_available
266 def update_resource_provider(self, resource_provider):
267 """Update the resource provider identified by uuid.
268
269 :param resource_provider: The resource provider. A dict with
270 the uuid (required),
271 the name (required) and
272 the parent_provider_uuid (optional).
273 :raises PlacementResourceProviderNotFound: No such resource provider.
274 :raises PlacementResourceProviderNameNotUnique: Conflict with another
275 resource provider with
276 the same name.
277 :returns: The updated resource provider.
278 """
279 # pylint: disable=raise-missing-from
280 url = '/resource_providers/{}'.format(resource_provider['uuid'])
281 # update does not tolerate if the uuid is repeated in the body
282 update_body = resource_provider.copy()
283 update_body.pop('uuid')
284 try:
285 return self._put(url, update_body).json()
286 except ks_exc.NotFound:
287 raise n_exc.PlacementResourceProviderNotFound(
288 resource_provider=resource_provider['uuid'])
289 except ks_exc.Conflict:
290 raise n_exc.PlacementResourceProviderNameNotUnique(
291 name=resource_provider['name'])
292
293 @_check_placement_api_available
294 def ensure_resource_provider(self, resource_provider):
295 """Ensure a resource provider exists by updating or creating it.
296
297 :param resource_provider: The resource provider. A dict with
298 the uuid (required),
299 the name (required) and
300 the parent_provider_uuid (optional).
301 :returns: The Resource Provider updated or created.
302
303 Beware, this is not an atomic operation of the API.
304 """
305 try:
306 return self.update_resource_provider(
307 resource_provider=resource_provider)
308 except n_exc.PlacementResourceProviderNotFound:
309 return self.create_resource_provider(resource_provider)
310
311 @_check_placement_api_available
312 def delete_resource_provider(self, resource_provider_uuid):
313 """Delete a resource provider.
314
315 :param resource_provider_uuid: UUID of the resource provider.
316 """
317 url = f'/resource_providers/{resource_provider_uuid}'
318 self._delete(url)
319
320 @_check_placement_api_available
321 def get_resource_provider(self, resource_provider_uuid):
322 """Get resource provider by UUID.
323
324 :param resource_provider_uuid: UUID of the resource provider.
325 :raises PlacementResourceProviderNotFound: For failure to find resource
326 :returns: The Resource Provider matching the UUID.
327 """
328 # pylint: disable=raise-missing-from
329 url = f'/resource_providers/{resource_provider_uuid}'
330 try:
331 return self._get(url).json()
332 except ks_exc.NotFound:
333 raise n_exc.PlacementResourceProviderNotFound(
334 resource_provider=resource_provider_uuid)
335
336 @_check_placement_api_available
337 def list_resource_providers(self, name=None, member_of=None,
338 resources=None, in_tree=None, uuid=None):
339 """Get a list of resource providers.
340
341 :param name: Name of the resource providers.
342 :param member_of: List of aggregate UUID to get those resource
343 providers that are associated with.
344 NOTE: placement 1.3 needed.
345 :param resources: Dictionary of resource classes and requested values.
346 :param in_tree: UUID of a resource provider that the caller wants to
347 limit the returned providers to those within its
348 'provider tree'. The returned list will contain only
349 resource providers with the root_provider_id of the
350 resource provider with UUID == tree_uuid.
351 NOTE: placement 1.14 needed.
352 :param uuid: UUID of the resource provider.
353 :raises PlacementAPIVersionIncorrect: If placement API target version
354 is too low
355 :returns: A list of Resource Provider matching the filters.
356 """
357 url = '/resource_providers'
358 filters = {}
359 if name:
360 filters['name'] = name
361 if member_of:
362 needed_version = _get_version(PLACEMENT_API_WITH_MEMBER_OF)
363 if self._target_version < needed_version:
364 raise n_exc.PlacementAPIVersionIncorrect(
365 current_version=self._target_version,
366 needed_version=needed_version)
367 filters['member_of'] = member_of
368 if resources:
369 filters['resources'] = resources
370 if in_tree:
371 needed_version = _get_version(
372 PLACEMENT_API_WITH_NESTED_RESOURCES)
373 if self._target_version < needed_version:
374 raise n_exc.PlacementAPIVersionIncorrect(
375 current_version=self._target_version,
376 needed_version=needed_version)
377 filters['in_tree'] = in_tree
378 if uuid:
379 filters['uuid'] = uuid
380 url = f'{url}?{parse.urlencode(filters)}'
381 return self._get(url).json()
382
383 @_check_placement_api_available
384 def update_resource_provider_inventories(
385 self, resource_provider_uuid, inventories,
386 resource_provider_generation=None):
387 """Replaces the set of inventory records for a resource provider.
388
389 :param resource_provider_uuid: UUID of the resource provider.
390 :param inventories: The inventories. A dict in the format (see:
391 Placement API ref: https://goo.gl/F22mtk)
392 {resource_class(required):
393 {allocation_ratio(required):
394 total(required):
395 max_unit(required):
396 min_unit(required):
397 reserved(required):
398 step_size(required):
399 }}
400 :param resource_provider_generation: The generation of the resource
401 provider. Optional.
402 :raises PlacementResourceProviderNotFound: if the resource provider
403 is not found.
404 :raises PlacementResourceProviderGenerationConflict: if the generation
405 of the resource
406 provider does not
407 match with the
408 server side.
409 :returns: The updated set of inventory records.
410 """
411 # pylint: disable=raise-missing-from
412 url = f'/resource_providers/{resource_provider_uuid}/inventories'
413 body = {
414 'resource_provider_generation': resource_provider_generation,
415 'inventories': inventories
416 }
417
418 try:
419 return self._put_with_retry_for_generation_conflict(
420 url, body, resource_provider_uuid,
421 resource_provider_generation)
422 except ks_exc.NotFound:
423 raise n_exc.PlacementResourceProviderNotFound(
424 resource_provider=resource_provider_uuid)
425
426 @_check_placement_api_available
427 def delete_resource_provider_inventories(self, resource_provider_uuid):
428 """Delete all inventory records for the resource provider.
429
430 :param resource_provider_uuid: UUID of the resource provider.
431 :raises PlacementResourceProviderNotFound: If the resource provider
432 is not found.
433 :returns: None.
434 """
435 url = f'/resource_providers/{resource_provider_uuid}/inventories'
436 try:
437 self._delete(url)
438 except ks_exc.NotFound as e:
439 if "No resource provider with uuid" in e.details:
440 raise n_exc.PlacementResourceProviderNotFound(
441 resource_provider=resource_provider_uuid)
442 raise
443
444 @_check_placement_api_available
445 def delete_resource_provider_inventory(self, resource_provider_uuid,
446 resource_class):
447 """Delete inventory of the resource class for a resource provider.
448
449 :param resource_provider_uuid: UUID of the resource provider.
450 :param resource_class: The name of the resource class
451 :raises PlacementResourceProviderNotFound: If the resource provider
452 is not found.
453 :raises PlacementInventoryNotFound: No inventory of class.
454 :returns: None.
455 """
456 url = (f'/resource_providers/{resource_provider_uuid}'
457 f'/inventories/{resource_class}')
458 try:
459 self._delete(url)
460 except ks_exc.NotFound as e:
461 if "No resource provider with uuid" in e.details:
462 raise n_exc.PlacementResourceProviderNotFound(
463 resource_provider=resource_provider_uuid)
464 if "No inventory of class" in e.details:
465 raise n_exc.PlacementInventoryNotFound(
466 resource_provider=resource_provider_uuid,
467 resource_class=resource_class)
468 raise
469
470 @_check_placement_api_available
471 def get_inventory(self, resource_provider_uuid, resource_class):
472 """Get resource provider inventory.
473
474 :param resource_provider_uuid: UUID of the resource provider.
475 :param resource_class: Resource class name of the inventory to be
476 returned.
477 :raises PlacementResourceProviderNotFound: If the resource provider is
478 not found.
479 :raises PlacementInventoryNotFound: For failure to find inventory
480 for a resource provider.
481 :returns: The inventory of the resource class as a dict.
482 """
483 url = (f'/resource_providers/{resource_provider_uuid}/'
484 f'inventories/{resource_class}')
485 try:
486 return self._get(url).json()
487 except ks_exc.NotFound as e:
488 if "No resource provider with uuid" in e.details:
489 raise n_exc.PlacementResourceProviderNotFound(
490 resource_provider=resource_provider_uuid)
491 if _("No inventory of class") in e.details:
492 raise n_exc.PlacementInventoryNotFound(
493 resource_provider=resource_provider_uuid,
494 resource_class=resource_class)
495 raise
496
497 @_check_placement_api_available
498 def update_resource_provider_inventory(
499 self, resource_provider_uuid, inventory, resource_class,
500 resource_provider_generation=None):
501 """Update resource provider inventory.
502
503 :param resource_provider_uuid: UUID of the resource provider.
504 :param inventory: The inventory to be updated for the resource class.
505 :param resource_class: The name of the resource class.
506 :param resource_provider_generation: The generation of the resource
507 provider. Optional.
508 :raises PlacementResourceNotFound: If the resource provider or the
509 resource class is not found.
510 :raises PlacementResourceProviderGenerationConflict: If the resource
511 provider
512 generation does
513 not match with the
514 server side.
515 :returns: The updated inventory of the resource class as a dict.
516 """
517 url = (f'/resource_providers/{resource_provider_uuid}/'
518 f'inventories/{resource_class}')
519 body = inventory
520
521 try:
522 return self._put_with_retry_for_generation_conflict(
523 url, body, resource_provider_uuid,
524 resource_provider_generation)
525 except ks_exc.NotFound as e:
526 raise n_exc.PlacementResourceNotFound(url=e.url)
527
528 @_check_placement_api_available
529 def associate_aggregates(self, resource_provider_uuid, aggregates):
530 """Associate a list of aggregates with a resource provider.
531
532 :param resource_provider_uuid: UUID of the resource provider.
533 :param aggregates: aggregates to be associated to the resource
534 provider.
535 :returns: All aggregates associated with the resource provider.
536 """
537 url = f'/resource_providers/{resource_provider_uuid}/aggregates'
538 return self._put(url, aggregates).json()
539
540 @_check_placement_api_available
541 def list_aggregates(self, resource_provider_uuid):
542 """List resource provider aggregates.
543
544 :param resource_provider_uuid: UUID of the resource provider.
545 :raises PlacementAggregateNotFound: For failure to the aggregates of
546 a resource provider.
547 :returns: The list of aggregates together with the resource provider
548 generation.
549 """
550 # pylint: disable=raise-missing-from
551 url = f'/resource_providers/{resource_provider_uuid}/aggregates'
552 try:
553 return self._get(url).json()
554 except ks_exc.NotFound:
555 raise n_exc.PlacementAggregateNotFound(
556 resource_provider=resource_provider_uuid)
557
558 @_check_placement_api_available
559 def list_traits(self):
560 """List all traits."""
561 url = '/traits'
562 return self._get(url).json()
563
564 @_check_placement_api_available
565 def get_trait(self, name):
566 """Check if a given trait exists
567
568 :param name: name of the trait to check.
569 :raises PlacementTraitNotFound: If the trait name not found.
570 :returns: Evaluates to True if the trait exists.
571 """
572 # pylint: disable=raise-missing-from
573 url = f'/traits/{name}'
574 try:
575 return self._get(url)
576 except ks_exc.NotFound:
577 raise n_exc.PlacementTraitNotFound(trait=name)
578
579 @_check_placement_api_available
580 def update_trait(self, name):
581 """Insert a single custom trait.
582
583 :param name: name of the trait to create.
584 :returns: The Response object so you may access response headers.
585 """
586 url = f'/traits/{name}'
587 return self._put(url, None)
588
589 @_check_placement_api_available
590 def delete_trait(self, name):
591 """Delete the specified trait.
592
593 :param name: the name of the trait to be deleted.
594 :raises PlacementTraitNotFound: If the trait did not exist.
595 :returns: None.
596 """
597 # pylint: disable=raise-missing-from
598 url = f'/traits/{name}'
599 try:
600 self._delete(url)
601 except ks_exc.NotFound:
602 raise n_exc.PlacementTraitNotFound(trait=name)
603
604 @_check_placement_api_available
605 def update_resource_provider_traits(
606 self, resource_provider_uuid, traits,
607 resource_provider_generation=None):
608 """Replace all associated traits of a resource provider.
609
610 :param resource_provider_uuid: UUID of the resource provider for which
611 to set the traits
612 :param traits: a list of traits.
613 :param resource_provider_generation: The generation of the resource
614 provider. Optional. If not
615 supplied by the caller, handle
616 potential generation conflict
617 by retrying the call. If supplied
618 we assume the caller handles
619 generation conflict.
620 :raises PlacementResourceProviderNotFound: If the resource provider
621 is not found.
622 :raises PlacementTraitNotFound: If any of the specified traits are not
623 valid.
624 :raises PlacementResourceProviderGenerationConflict: For concurrent
625 conflicting
626 updates detected.
627 :returns: The new traits of the resource provider together with the
628 resource provider generation.
629 """
630 # pylint: disable=raise-missing-from
631 url = f'/resource_providers/{resource_provider_uuid}/traits'
632 body = {
633 'resource_provider_generation': resource_provider_generation,
634 'traits': traits
635 }
636
637 try:
638 return self._put_with_retry_for_generation_conflict(
639 url, body, resource_provider_uuid,
640 resource_provider_generation)
641 except ks_exc.NotFound:
642 raise n_exc.PlacementResourceProviderNotFound(
643 resource_provider=resource_provider_uuid)
644 except ks_exc.BadRequest:
645 raise n_exc.PlacementTraitNotFound(trait=traits)
646
647 @_check_placement_api_available
648 def list_resource_provider_traits(self, resource_provider_uuid):
649 """List all traits associated with a resource provider
650
651 :param resource_provider_uuid: UUID of the resource provider for which
652 the traits will be listed
653 :raises PlacementResourceProviderNotFound: If the resource provider
654 is not found.
655 :returns: The associated traits of the resource provider together
656 with the resource provider generation.
657 """
658 # pylint: disable=raise-missing-from
659 url = f'/resource_providers/{resource_provider_uuid}/traits'
660 try:
661 return self._get(url).json()
662 except ks_exc.NotFound:
663 raise n_exc.PlacementResourceProviderNotFound(
664 resource_provider=resource_provider_uuid)
665
666 @_check_placement_api_available
667 def delete_resource_provider_traits(self, resource_provider_uuid):
668 """Delete resource provider traits.
669
670 :param resource_provider_uuid: The UUID of the resource provider for
671 which to delete all the traits.
672 :raises PlacementResourceProviderNotFound: If the resource provider
673 is not found.
674 :returns: None.
675 """
676 # pylint: disable=raise-missing-from
677 url = f'/resource_providers/{resource_provider_uuid}/traits'
678 try:
679 self._delete(url)
680 except ks_exc.NotFound:
681 raise n_exc.PlacementResourceProviderNotFound(
682 resource_provider=resource_provider_uuid)
683
684 @_check_placement_api_available
685 def list_resource_classes(self):
686 """List resource classes"""
687 url = '/resource_classes'
688 return self._get(url).json()
689
690 @_check_placement_api_available
691 def get_resource_class(self, name):
692 """Show resource class.
693
694 :param name: The name of the resource class to show
695 :raises PlacementResourceClassNotFound: If the resource class
696 is not found.
697 :returns: The name of resource class and its set of links.
698 """
699 # pylint: disable=raise-missing-from
700 url = f'/resource_classes/{name}'
701 try:
702 return self._get(url).json()
703 except ks_exc.NotFound:
704 raise n_exc.PlacementResourceClassNotFound(resource_class=name)
705
706 @_check_placement_api_available
707 def create_resource_class(self, name):
708 """Create a custom resource class
709
710 :param name: the name of the resource class
711 :returns: None.
712 """
713 url = '/resource_classes'
714 body = {'name': name}
715 self._post(url, body)
716
717 @_check_placement_api_available
718 def update_resource_class(self, name):
719 """Create or validate the existence of the resource custom class.
720
721 :param name: the name of the resource class to be updated or validated
722 :returns: None.
723 """
724 url = f'/resource_classes/{name}'
725 self._put(url, None)
726
727 @_check_placement_api_available
728 def delete_resource_class(self, name):
729 """Delete a custom resource class.
730
731 :param name: The name of the resource class to be deleted.
732 :raises PlacementResourceClassNotFound: If the resource class
733 is not found.
734 :returns: None.
735 """
736 # pylint: disable=raise-missing-from
737 url = f'/resource_classes/{name}'
738 try:
739 self._delete(url)
740 except ks_exc.NotFound:
741 raise n_exc.PlacementResourceClassNotFound(resource_class=name)
742
743 @_check_placement_api_available
744 def list_allocations(self, consumer_uuid):
745 """List allocations for the consumer
746
747 :param consumer_uuid: The uuid of the consumer, in case of bound port
748 owned by a VM, the VM uuid.
749 :returns: All allocation records for the consumer.
750 """
751 url = f'/allocations/{consumer_uuid}'
752 return self._get(url).json()
753
754 def update_qos_allocation(self, consumer_uuid, alloc_diff):
755 """Update allocation for QoS minimum bandwidth consumer
756
757 :param consumer_uuid: The uuid of the consumer, in case of bound port
758 owned by a VM, the VM uuid.
759 :param alloc_diff: A dict which contains RP UUIDs as keys and
760 corresponding fields to update for the allocation
761 under the given resource provider.
762 """
763 for i in range(GENERATION_CONFLICT_RETRIES):
764 body = self.list_allocations(consumer_uuid)
765 if not body['allocations']:
766 raise n_exc.PlacementAllocationRemoved(consumer=consumer_uuid)
767 # Count new values based on the diff in alloc_diff
768 for rp_uuid, diff in alloc_diff.items():
769 if rp_uuid not in body['allocations']:
770 raise n_exc.PlacementAllocationRpNotExists(
771 resource_provider=rp_uuid, consumer=consumer_uuid)
772 for drctn, value in diff.items():
773 orig_value = body['allocations'][rp_uuid][
774 'resources'].get(drctn, 0)
775 new_value = orig_value + value
776 if new_value > 0:
777 body['allocations'][rp_uuid]['resources'][
778 drctn] = new_value
779 else:
780 # Remove the resource class if the new value is 0
781 resources = body['allocations'][rp_uuid]['resources']
782 resources.pop(drctn, None)
783
784 # Remove RPs without any resources
785 body['allocations'] = {
786 rp: alloc for rp, alloc in body['allocations'].items()
787 if alloc.get('resources')}
788 try:
789 # Update allocations has no return body, but leave the loop
790 return self.update_allocation(consumer_uuid, body)
791 except ks_exc.Conflict as e:
792 resp = e.response.json()
793 if resp['errors'][0]['code'] == 'placement.concurrent_update':
794 continue
795 raise
796 raise n_exc.PlacementAllocationGenerationConflict(
797 consumer=consumer_uuid)
798
799 def update_allocation(self, consumer_uuid, allocations):
800 """Update allocation record for given consumer and rp
801
802 :param consumer_uuid: The uuid of the consumer
803 :param allocations: Dict in the form described in placement API ref:
804 https://tinyurl.com/yxeuzn6l
805 """
806 url = f'/allocations/{consumer_uuid}'
807 self._put(url, allocations)