blob: 3506c6dcc70a41b57d6c6c21a4a347c8fc078840 [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
14def named_checker(resource, ref, cloud_name):
15 resp_key = response_keys[resource]
16 resp = resource_lists[resource](
17 name=ref, cloud_name=cloud_name)
18 try:
19 resp = resp[resp_key]
20 except KeyError:
21 raise common.ResourceNotFound(resp_key, ref)
22 if len(resp) == 0:
23 raise common.ResourceNotFound(resp_key, ref)
24 elif len(resp) > 1:
25 raise common.MultipleResourcesFound(resp_key, ref)
26 return resp[0]['id']
27
28
29def nameless_checker(resource, ref, cloud_name):
30 item_id = None
31 resp_key = response_keys[resource]
32 resp = resource_lists[resource](cloud_name=cloud_name)
33 try:
34 resp = resp[resp_key]
35 except KeyError:
36 raise common.ResourceNotFound(resp_key, ref)
37 for item in resp:
38 if item["name"] == ref:
39 if item_id is not None:
40 raise common.MultipleResourcesFound(resp_key, ref)
41 item_id = item["id"]
42 if not item_id:
43 raise common.ResourceNotFound(resp_key, ref)
44 return item_id
45
46
47
48resource_lists = {
49 'volume': lists.volume_list,
50 'volume_type': lists.volume_type_list
51}
52
53
54response_keys = {
55 'volume': 'volumes',
56 'volume_type': 'volume_types',
57}
58
59
60name_checkers = {
61 'volume': named_checker,
62 'volume_type': nameless_checker,
63}
64
65
66def get_by_name_or_uuid_multiple(resource_arg_name_pairs):
67 def wrap(func):
68 def wrapped_f(*args, **kwargs):
69 results = []
70 args_start = 0
71 for index, (resource, arg_name) in enumerate(
72 resource_arg_name_pairs):
73 if arg_name in kwargs:
74 ref = kwargs.pop(arg_name, None)
75 else:
76 ref = args[index]
77 args_start += 1
78 cloud_name = kwargs['cloud_name']
79 checker = CheckId()
80 if checker.check_id(ref):
81 results.append(ref)
82 else:
83 # Then we have name not uuid
84 res = name_checkers[resource](resource, ref, cloud_name)
85 results.append(res)
86 results.extend(args[args_start:])
87 return func(*results, **kwargs)
88 return wrapped_f
89 return wrap