blob: 79d93a0bce3d6747de17b59f4a7d198e989a7410 [file] [log] [blame]
Oleksiy Petrenko2652ac12018-04-16 17:40:13 +03001import logging
2import os_client_config
3from uuid import UUID
4
5log = logging.getLogger(__name__)
6
7
8class GlanceException(Exception):
9
10 _msg = "Glance module exception occured."
11
12 def __init__(self, message=None, **kwargs):
13 super(GlanceException, self).__init__(message or self._msg)
14
15
16class NoGlanceEndpoint(GlanceException):
17 _msg = "Glance endpoint not found in keystone catalog."
18
19
20class NoAuthPluginConfigured(GlanceException):
21 _msg = ("You are using keystoneauth auth plugin that does not support "
22 "fetching endpoint list from token (noauth or admin_token).")
23
24
25class NoCredentials(GlanceException):
26 _msg = "Please provide cloud name present in clouds.yaml."
27
28
29class ResourceNotFound(GlanceException):
30 _msg = "Uniq resource: {resource} with name: {name} not found."
31
32 def __init__(self, resource, name, **kwargs):
33 super(GlanceException, self).__init__(
34 self._msg.format(resource=resource, name=name))
35
36
37class MultipleResourcesFound(GlanceException):
38 _msg = "Multiple resource: {resource} with name: {name} found."
39
40 def __init__(self, resource, name, **kwargs):
41 super(GlanceException, self).__init__(
42 self._msg.format(resource=resource, name=name))
43
44
45def get_raw_client(cloud_name):
46 service_type = 'image'
Oleh Hryhorov6de49c92018-05-21 12:53:59 +000047 config = os_client_config.OpenStackConfig()
48 cloud = config.get_one_cloud(cloud_name)
49 adapter = cloud.get_session_client(service_type)
50 adapter.version = '2'
Oleksiy Petrenko2652ac12018-04-16 17:40:13 +030051 try:
52 access_info = adapter.session.auth.get_access(adapter.session)
53 endpoints = access_info.service_catalog.get_endpoints()
Oleh Hryhorov6de49c92018-05-21 12:53:59 +000054 except (AttributeError, ValueError) as exc:
55 log.exception('%s' % exc)
Oleksiy Petrenko2652ac12018-04-16 17:40:13 +030056 e = NoAuthPluginConfigured()
57 log.exception('%s' % e)
58 raise e
59 if service_type not in endpoints:
60 if not service_type:
61 e = NoGlanceEndpoint()
62 log.error('%s' % e)
63 raise e
64 return adapter
65
66
67def send(method):
68 def wrap(func):
69 def wrapped_f(*args, **kwargs):
70 cloud_name = kwargs.pop('cloud_name')
71 if not cloud_name:
72 e = NoCredentials()
73 log.error('%s' % e)
74 raise e
75 adapter = get_raw_client(cloud_name)
76 # Remove salt internal kwargs
77 kwarg_keys = list(kwargs.keys())
78 for k in kwarg_keys:
79 if k.startswith('__'):
80 kwargs.pop(k)
81 url, request_kwargs = func(*args, **kwargs)
82 response = getattr(adapter, method)(url, **request_kwargs)
83 if not response.content:
84 return {}
85 return response.json()
86 return wrapped_f
87 return wrap
88
89
90def _check_uuid(val):
91 try:
92 return str(UUID(val)).replace('-', '') == val.replace('-', '')
93 except (TypeError, ValueError, AttributeError):
94 return False
95
96
97def get_by_name_or_uuid(resource_list, resp_key):
98 def wrap(func):
99 def wrapped_f(*args, **kwargs):
100 if 'name' in kwargs:
101 ref = kwargs.pop('name', None)
102 start_arg = 0
103 else:
104 start_arg = 1
105 ref = args[0]
106 if _check_uuid(ref):
107 uuid = ref
108 else:
109 # Then we have name not uuid
110 cloud_name = kwargs['cloud_name']
111 resp = resource_list(
112 name=ref, cloud_name=cloud_name)[resp_key]
113 if len(resp) == 0:
114 raise ResourceNotFound(resp_key, ref)
115 elif len(resp) > 1:
116 raise MultipleResourcesFound(resp_key, ref)
117 uuid = resp[0]['id']
118 return func(uuid, *args[start_arg:], **kwargs)
119 return wrapped_f
120 return wrap