blob: 0dd4b8e84f72436754db6c5089cddcde35436a31 [file] [log] [blame]
Oleksiy Petrenko5bfb8bc2018-08-23 15:08:17 +03001import functools
Oleksiy Petrenkocaad2032018-04-20 14:42:46 +03002import logging
3import os_client_config
Oleksiy Petrenkocaad2032018-04-20 14:42:46 +03004
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):
Oleksiy Petrenko5bfb8bc2018-08-23 15:08:17 +030066 @functools.wraps(func)
Oleksiy Petrenkocaad2032018-04-20 14:42:46 +030067 def wrapped_f(*args, **kwargs):
68 cloud_name = kwargs.pop('cloud_name')
69 if not cloud_name:
70 e = NoCredentials()
71 log.error('%s' % e)
72 raise e
73 adapter = _get_raw_client(cloud_name)
74 # Remove salt internal kwargs
75 kwarg_keys = list(kwargs.keys())
76 for k in kwarg_keys:
77 if k.startswith('__'):
78 kwargs.pop(k)
79 url, request_kwargs = func(*args, **kwargs)
80 if 'microversion' in kwargs:
81 request_kwargs['headers'][
82 NEUTRON_VERSION_HEADER] = kwargs['microversion']
83 response = getattr(adapter, method)(url, **request_kwargs)
84 if not response.content:
85 return {}
86 try:
87 resp = response.json()
88 except ValueError:
89 resp = response.content
90 return resp
91 return wrapped_f
92 return wrap