blob: 90445fd3d818ca995e6b840084a5f2026beb5621 [file] [log] [blame]
Oleksiy Petrenkoe38f5a62018-11-21 12:58:07 +02001import uuid
2from cinderv3 import common
3from cinderv3 import lists
4
5
6class CheckId(object):
7 def check_id(self, val):
8 try:
9 return str(uuid.UUID(val)) == val
10 except (TypeError, ValueError, AttributeError):
11 return False
12
13
root08402652018-12-28 15:04:23 +000014def named_checker(resource, ref, cloud_name, **kwargs):
Oleksiy Petrenkoe38f5a62018-11-21 12:58:07 +020015 resp_key = response_keys[resource]
16 resp = resource_lists[resource](
root08402652018-12-28 15:04:23 +000017 name=ref, cloud_name=cloud_name, **kwargs)[resp_key]
Oleksiy Petrenkoe38f5a62018-11-21 12:58:07 +020018 if len(resp) == 0:
19 raise common.ResourceNotFound(resp_key, ref)
20 elif len(resp) > 1:
21 raise common.MultipleResourcesFound(resp_key, ref)
22 return resp[0]['id']
23
24
root08402652018-12-28 15:04:23 +000025def nameless_checker(resource, ref, cloud_name, **kwargs):
Oleksiy Petrenkoe38f5a62018-11-21 12:58:07 +020026 item_id = None
27 resp_key = response_keys[resource]
root08402652018-12-28 15:04:23 +000028 resp = resource_lists[resource](
29 cloud_name=cloud_name, **kwargs)[resp_key]
Oleksiy Petrenkoe38f5a62018-11-21 12:58:07 +020030 for item in resp:
31 if item["name"] == ref:
32 if item_id is not None:
33 raise common.MultipleResourcesFound(resp_key, ref)
34 item_id = item["id"]
35 if not item_id:
36 raise common.ResourceNotFound(resp_key, ref)
37 return item_id
38
39
40
41resource_lists = {
42 'volume': lists.volume_list,
43 'volume_type': lists.volume_type_list
44}
45
46
47response_keys = {
48 'volume': 'volumes',
49 'volume_type': 'volume_types',
50}
51
52
53name_checkers = {
54 'volume': named_checker,
55 'volume_type': nameless_checker,
56}
57
58
59def get_by_name_or_uuid_multiple(resource_arg_name_pairs):
60 def wrap(func):
61 def wrapped_f(*args, **kwargs):
62 results = []
63 args_start = 0
root08402652018-12-28 15:04:23 +000064 connection_params = kwargs.pop('connection_params', {}) or {}
Oleksiy Petrenkoe38f5a62018-11-21 12:58:07 +020065 for index, (resource, arg_name) in enumerate(
66 resource_arg_name_pairs):
67 if arg_name in kwargs:
68 ref = kwargs.pop(arg_name, None)
69 else:
70 ref = args[index]
71 args_start += 1
72 cloud_name = kwargs['cloud_name']
73 checker = CheckId()
74 if checker.check_id(ref):
75 results.append(ref)
76 else:
77 # Then we have name not uuid
root08402652018-12-28 15:04:23 +000078 res = name_checkers[resource](resource, ref, cloud_name,
79 connection_params=connection_params)
Oleksiy Petrenkoe38f5a62018-11-21 12:58:07 +020080 results.append(res)
81 results.extend(args[args_start:])
82 return func(*results, **kwargs)
83 return wrapped_f
root08402652018-12-28 15:04:23 +000084 return wrap