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