Set MTU=1442 in ansible_utils_tests.py
[snaps.git] / snaps / openstack / os_credentials.py
1 # Copyright (c) 2017 Cable Television Laboratories, Inc. ("CableLabs")
2 #                    and others.  All rights reserved.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at:
7 #
8 #     http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 from neutronclient.common.utils import str2bool
16 import numbers
17 from snaps import file_utils
18 from snaps.openstack.utils import glance_utils, keystone_utils, cinder_utils
19
20 __author__ = 'spisarski'
21
22
23 class OSCreds:
24     """
25     Represents the credentials required to connect with OpenStack servers
26     """
27
28     def __init__(self, **kwargs):
29         """
30         Constructor
31         :param username: The user (required)
32         :param password: The user's password (required)
33         :param auth_url: The OpenStack cloud's authorization URL (required)
34         :param project_name: The project/tenant name
35         :param identity_api_version: The OpenStack's API version to use for
36                                      Keystone clients
37         :param image_api_version: The OpenStack's API version to use for Glance
38                                   clients
39         :param network_api_version: The OpenStack's API version to use for
40                                     Neutron clients
41         :param compute_api_version: The OpenStack's API version to use for Nova
42                                     clients
43         :param heat_api_version: The OpenStack's API version to use for Heat
44                                     clients
45         :param volume_api_version: The OpenStack's API version to use
46                                    for Cinder clients
47         :param magnum_api_version: The OpenStack's API version to use
48                                    for magnum clients
49         :param user_domain_id: Used for v3 APIs (default='default')
50         :param user_domain_name: Used for v3 APIs (default='Default')
51         :param project_domain_id: Used for v3 APIs (default='default')
52         :param project_domain_name: Used for v3 APIs (default='Default')
53         :param interface: Used to specify the endpoint type for keystone as
54                           public, admin, internal
55         :param proxy_settings: instance of os_credentials.ProxySettings class
56         :param cacert: True for https or the certification file for https
57                        verification (default=False)
58         :param region_name: the region (optional default = None)
59         """
60         self.username = kwargs.get('username')
61         self.password = kwargs.get('password')
62         self.auth_url = kwargs.get('auth_url')
63         self.project_name = kwargs.get('project_name')
64
65         if kwargs.get('identity_api_version') is None:
66             self.identity_api_version = keystone_utils.V3_VERSION_NUM
67         else:
68             self.identity_api_version = float(kwargs['identity_api_version'])
69
70         if kwargs.get('image_api_version') is None:
71             self.image_api_version = glance_utils.VERSION_2
72         else:
73             self.image_api_version = float(kwargs['image_api_version'])
74
75         if kwargs.get('network_api_version') is None:
76             self.network_api_version = 2
77         else:
78             self.network_api_version = float(kwargs['network_api_version'])
79
80         if kwargs.get('compute_api_version') is None:
81             self.compute_api_version = 2
82         else:
83             self.compute_api_version = float(kwargs['compute_api_version'])
84
85         if kwargs.get('heat_api_version') is None:
86             self.heat_api_version = 1
87         else:
88             val = kwargs['heat_api_version']
89             ver = float(val)
90             self.heat_api_version = int(ver)
91
92         if kwargs.get('volume_api_version') is None:
93             self.volume_api_version = cinder_utils.VERSION_2
94         else:
95             self.volume_api_version = float(kwargs['volume_api_version'])
96
97         if kwargs.get('magnum_api_version') is None:
98             self.magnum_api_version = 1
99         else:
100             self.magnum_api_version = float(kwargs['magnum_api_version'])
101
102         self.user_domain_id = kwargs.get('user_domain_id', 'default')
103
104         if kwargs.get('user_domain_name') is None:
105             self.user_domain_name = 'Default'
106         else:
107             self.user_domain_name = kwargs['user_domain_name']
108
109         self.project_domain_id = kwargs.get('project_domain_id', 'default')
110
111         if kwargs.get('project_domain_name') is None:
112             self.project_domain_name = 'Default'
113         else:
114             self.project_domain_name = kwargs['project_domain_name']
115
116         if kwargs.get('interface') is None:
117             self.interface = 'public'
118         else:
119             self.interface = kwargs['interface']
120
121         self.region_name = kwargs.get('region_name', None)
122
123         self.cacert = False
124         if kwargs.get('cacert') is not None:
125             if isinstance(kwargs.get('cacert'), str):
126                 if file_utils.file_exists(kwargs['cacert']):
127                     self.cacert = kwargs['cacert']
128                 else:
129                     self.cacert = str2bool(kwargs['cacert'])
130             else:
131                 self.cacert = kwargs['cacert']
132
133         if isinstance(kwargs.get('proxy_settings'), ProxySettings):
134             self.proxy_settings = kwargs.get('proxy_settings')
135         elif isinstance(kwargs.get('proxy_settings'), dict):
136             self.proxy_settings = ProxySettings(**kwargs.get('proxy_settings'))
137         else:
138             self.proxy_settings = None
139
140         if (not self.username or not self.password or not self.auth_url
141                 or not self.project_name):
142             raise OSCredsError('username, password, auth_url, and project_name'
143                                ' are required')
144
145         self.auth_url = self.__scrub_auth_url()
146
147     def __scrub_auth_url(self):
148         """
149         As the Python APIs are have more stringent requirements around how the
150         auth_url is formed than the CLI, this method will scrub any version
151         from the end of
152         :return:
153         """
154         auth_url_tokens = self.auth_url.rstrip('/').split('/')
155         last_token = auth_url_tokens[len(auth_url_tokens) - 1]
156         token_iters = len(auth_url_tokens)
157         if last_token.startswith('v'):
158             token_iters -= 1
159         if self.identity_api_version == keystone_utils.V2_VERSION_NUM:
160             last_token = keystone_utils.V2_VERSION_STR
161         else:
162             last_token = 'v' + str(int(self.identity_api_version))
163
164         new_url = None
165         for ctr in range(0, token_iters):
166             if new_url:
167                 new_url += '/' + auth_url_tokens[ctr]
168             else:
169                 new_url = auth_url_tokens[ctr]
170         new_url += '/' + last_token
171
172         return new_url
173
174     def to_dict(self):
175         """Converts object to a dict that can be used to construct another"""
176         return {'username': self.username,
177                 'password': self.password,
178                 'auth_url': self.auth_url,
179                 'project_name': self.project_name,
180                 'identity_api_version': self.identity_api_version,
181                 'image_api_version': self.image_api_version,
182                 'network_api_version': self.network_api_version,
183                 'compute_api_version': self.compute_api_version,
184                 'heat_api_version': self.heat_api_version,
185                 'user_domain_id': self.user_domain_id,
186                 'user_domain_name': self.user_domain_name,
187                 'project_domain_id': self.project_domain_id,
188                 'project_domain_name': self.project_domain_name,
189                 'interface': self.interface,
190                 'region_name': self.region_name,
191                 'proxy_settings': self.proxy_settings,
192                 'cacert': self.cacert}
193
194     def __eq__(self, other):
195         return (self.username == other.username and
196                 self.password == other.password and
197                 self.auth_url == other.auth_url and
198                 self.project_name == other.project_name and
199                 float(self.identity_api_version) == float(other.identity_api_version) and
200                 float(self.image_api_version) == float(other.image_api_version) and
201                 float(self.network_api_version) == float(other.network_api_version) and
202                 float(self.compute_api_version) == float(other.compute_api_version) and
203                 float(self.heat_api_version) == float(other.heat_api_version) and
204                 self.user_domain_id == other.user_domain_id and
205                 self.user_domain_name == other.user_domain_name and
206                 self.project_domain_id == other.project_domain_id and
207                 self.project_domain_name == other.project_domain_name and
208                 self.interface == other.interface and
209                 self.region_name == other.region_name and
210                 self.proxy_settings == other.proxy_settings and
211                 self.cacert == other.cacert)
212
213     def __str__(self):
214         """Converts object to a string"""
215         return ('OSCreds - username=' + str(self.username) +
216                 ', password=' + str(self.password) +
217                 ', auth_url=' + str(self.auth_url) +
218                 ', project_name=' + str(self.project_name) +
219                 ', identity_api_version=' + str(self.identity_api_version) +
220                 ', image_api_version=' + str(self.image_api_version) +
221                 ', network_api_version=' + str(self.network_api_version) +
222                 ', compute_api_version=' + str(self.compute_api_version) +
223                 ', heat_api_version=' + str(self.heat_api_version) +
224                 ', user_domain_id=' + str(self.user_domain_id) +
225                 ', user_domain_name=' + str(self.user_domain_name) +
226                 ', project_domain_id=' + str(self.project_domain_id) +
227                 ', project_domain_name=' + str(self.project_domain_name) +
228                 ', interface=' + str(self.interface) +
229                 ', region_name=' + str(self.region_name) +
230                 ', proxy_settings=' + str(self.proxy_settings) +
231                 ', cacert=' + str(self.cacert))
232
233
234 class ProxySettings:
235     """
236     Represents the information required for sending traffic (HTTP & SSH)
237     through a proxy
238     """
239
240     def __init__(self, **kwargs):
241         """
242         Constructor
243         :param host: the HTTP proxy host
244         :param port: the HTTP proxy port
245         :param https_host: the HTTPS proxy host (defaults to host)
246         :param https_port: the HTTPS proxy port (defaults to port)
247         :param ssh_proxy_cmd: the SSH proxy command string (optional)
248         """
249         self.host = kwargs.get('host')
250         self.port = kwargs.get('port')
251         if self.port and isinstance(self.port, numbers.Number):
252             self.port = str(self.port)
253
254         self.https_host = kwargs.get('https_host', self.host)
255         self.https_port = kwargs.get('https_port', self.port)
256         if self.https_port and isinstance(self.https_port, numbers.Number):
257             self.https_port = str(self.https_port)
258
259         self.ssh_proxy_cmd = kwargs.get('ssh_proxy_cmd')
260
261         if not self.host or not self.port:
262             raise ProxySettingsError('host & port are required')
263
264     def __str__(self):
265         """Converts object to a string"""
266         return 'ProxySettings - host=' + str(self.host) + \
267                ', port=' + str(self.port) + \
268                ', ssh_proxy_cmd=' + str(self.ssh_proxy_cmd)
269
270
271 class ProxySettingsError(Exception):
272     """
273     Exception to be thrown when an OSCred are invalid
274     """
275
276
277 class OSCredsError(Exception):
278     """
279     Exception to be thrown when an OSCred are invalid
280     """