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