blob: b2a60717c28e1fd221d6d6eef8b46d1a9d88583a [file] [log] [blame]
Oleksiy Petrenkoa5eb0602018-07-26 15:12:25 +03001import logging
2import os_client_config
3
4log = logging.getLogger(__name__)
5
6IRONIC_VERSION_HEADER = 'X-OpenStack-Ironic-API-Version'
7ADAPTER_VERSION = '1.0'
8
9
10class IronicException(Exception):
11
12 _msg = "Ironic module exception occurred."
13
14 def __init__(self, message=None, **kwargs):
15 super(IronicException, self).__init__(message or self._msg)
16
17
18class NoIronicEndpoint(IronicException):
19 _msg = "Ironic endpoint not found in keystone catalog."
20
21
22class NoAuthPluginConfigured(IronicException):
23 _msg = ("You are using keystoneauth auth plugin that does not support "
24 "fetching endpoint list from token (noauth or admin_token).")
25
26
27class NoCredentials(IronicException):
28 _msg = "Please provide cloud name present in clouds.yaml."
29
30
31def _get_raw_client(cloud_name):
32 service_type = 'baremetal'
33 config = os_client_config.OpenStackConfig()
34 cloud = config.get_one_cloud(cloud_name)
35 adapter = cloud.get_session_client(service_type)
36 adapter.version = ADAPTER_VERSION
37 try:
38 access_info = adapter.session.auth.get_access(adapter.session)
39 access_info.service_catalog.get_endpoints()
40 except (AttributeError, ValueError):
41 e = NoAuthPluginConfigured()
42 log.exception('%s' % e)
43 raise e
44 return adapter
45
46
47def send(method):
48 def wrap(func):
49 def wrapped_f(*args, **kwargs):
50 cloud_name = kwargs.pop('cloud_name')
51 if not cloud_name:
52 e = NoCredentials()
53 log.error('%s' % e)
54 raise e
55 adapter = _get_raw_client(cloud_name)
56 # Remove salt internal kwargs
57 kwarg_keys = list(kwargs.keys())
58 for k in kwarg_keys:
59 if k.startswith('__'):
60 kwargs.pop(k)
61 microversion = kwargs.pop('microversion', None)
62 url, request_kwargs = func(*args, **kwargs)
63 if microversion:
64 if 'headers' not in request_kwargs:
65 request_kwargs['headers'] = {}
66 request_kwargs['headers'][IRONIC_VERSION_HEADER] = \
67 microversion
68 response = getattr(adapter, method)(url, **request_kwargs)
69 if not response.content:
70 return {}
71 try:
72 resp = response.json()
73 except ValueError:
74 resp = response.content
75 return resp
76 return wrapped_f
77 return wrap