1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
|
# Copyright (c) 2017 Cable Television Laboratories, Inc. ("CableLabs")
# and others. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from neutronclient.common.exceptions import NotFound
from snaps.openstack.openstack_creator import OpenStackNetworkObject
from snaps.openstack.utils import keystone_utils, neutron_utils
__author__ = 'spisarski'
logger = logging.getLogger('OpenStackNetwork')
class OpenStackNetwork(OpenStackNetworkObject):
"""
Class responsible for managing a network in OpenStack
"""
def __init__(self, os_creds, network_settings):
"""
Constructor - all parameters are required
:param os_creds: The credentials to connect with OpenStack
:param network_settings: The settings used to create a network
"""
super(self.__class__, self).__init__(os_creds)
self.network_settings = network_settings
# Attributes instantiated on create()
self.__network = None
self.__subnets = list()
def initialize(self):
"""
Loads the existing OpenStack network/subnet
:return: The Network domain object or None
"""
super(self.__class__, self).initialize()
self.__network = neutron_utils.get_network(
self._neutron, network_settings=self.network_settings,
project_id=self.network_settings.get_project_id(self._os_creds))
if self.__network:
for subnet_setting in self.network_settings.subnet_settings:
sub_inst = neutron_utils.get_subnet(
self._neutron, subnet_settings=subnet_setting)
if sub_inst:
self.__subnets.append(sub_inst)
logger.debug(
"Subnet '%s' created successfully" % sub_inst.id)
return self.__network
def create(self):
"""
Responsible for creating not only the network but then a private
subnet, router, and an interface to the router.
:return: the Network domain object
"""
self.initialize()
if not self.__network:
self.__network = neutron_utils.create_network(
self._neutron, self._os_creds, self.network_settings)
logger.debug(
"Network '%s' created successfully" % self.__network.id)
for subnet_setting in self.network_settings.subnet_settings:
sub_inst = neutron_utils.get_subnet(
self._neutron, subnet_settings=subnet_setting)
if not sub_inst:
sub_inst = neutron_utils.create_subnet(
self._neutron, subnet_setting, self._os_creds,
self.__network)
if sub_inst:
self.__subnets.append(sub_inst)
logger.debug(
"Subnet '%s' created successfully" % sub_inst.id)
return self.__network
def clean(self):
"""
Removes and deletes all items created in reverse order.
"""
for subnet in self.__subnets:
try:
logger.info(
'Deleting subnet with name ' + subnet.name)
neutron_utils.delete_subnet(self._neutron, subnet)
except NotFound as e:
logger.warning(
'Error deleting subnet with message - ' + str(e))
pass
self.__subnets = list()
if self.__network:
try:
neutron_utils.delete_network(self._neutron, self.__network)
except NotFound:
pass
self.__network = None
def get_network(self):
"""
Returns the created OpenStack network object
:return: the OpenStack network object
"""
return self.__network
def get_subnets(self):
"""
Returns the OpenStack subnet objects
:return:
"""
return self.__subnets
class NetworkSettings:
"""
Class representing a network configuration
"""
def __init__(self, **kwargs):
"""
Constructor - all parameters are optional
:param name: The network name.
:param admin_state_up: The administrative status of the network.
True = up / False = down (default True)
:param shared: Boolean value indicating whether this network is shared
across all projects/tenants. By default, only
administrative users can change this value.
:param project_name: Admin-only. The name of the project that will own
the network. This project can be different from
the project that makes the create network request.
However, only administrative users can specify a
project ID other than their own. You cannot change
this value through authorization policies.
:param external: when true, will setup an external network
(default False).
:param network_type: the type of network (i.e. vlan|flat).
:param physical_network: the name of the physical network
(required when network_type is 'flat')
:param segmentation_id: the id of the segmentation
(this is required when network_type is 'vlan')
:param subnets or subnet_settings: List of SubnetSettings objects.
:return:
"""
self.project_id = None
self.name = kwargs.get('name')
if kwargs.get('admin_state_up') is not None:
self.admin_state_up = bool(kwargs['admin_state_up'])
else:
self.admin_state_up = True
if kwargs.get('shared') is not None:
self.shared = bool(kwargs['shared'])
else:
self.shared = None
self.project_name = kwargs.get('project_name')
if kwargs.get('external') is not None:
self.external = bool(kwargs.get('external'))
else:
self.external = False
self.network_type = kwargs.get('network_type')
self.physical_network = kwargs.get('physical_network')
self.segmentation_id = kwargs.get('segmentation_id')
self.subnet_settings = list()
subnet_settings = kwargs.get('subnets')
if not subnet_settings:
subnet_settings = kwargs.get('subnet_settings')
if subnet_settings:
for subnet_config in subnet_settings:
if isinstance(subnet_config, SubnetSettings):
self.subnet_settings.append(subnet_config)
else:
self.subnet_settings.append(
SubnetSettings(**subnet_config['subnet']))
if not self.name or len(self.name) < 1:
raise NetworkSettingsError('Name required for networks')
def get_project_id(self, os_creds):
"""
Returns the project ID for a given project_name or None
:param os_creds: the credentials required for keystone client retrieval
:return: the ID or None
"""
if self.project_id:
return self.project_id
else:
if self.project_name:
keystone = keystone_utils.keystone_client(os_creds)
project = keystone_utils.get_project(
keystone=keystone, project_name=self.project_name)
if project:
return project.id
return None
def dict_for_neutron(self, os_creds):
"""
Returns a dictionary object representing this object.
This is meant to be converted into JSON designed for use by the Neutron
API
TODO - expand automated testing to exercise all parameters
:param os_creds: the OpenStack credentials
:return: the dictionary object
"""
out = dict()
if self.name:
out['name'] = self.name
if self.admin_state_up is not None:
out['admin_state_up'] = self.admin_state_up
if self.shared:
out['shared'] = self.shared
if self.project_name:
project_id = self.get_project_id(os_creds)
if project_id:
out['tenant_id'] = project_id
else:
raise NetworkSettingsError(
'Could not find project ID for project named - ' +
self.project_name)
if self.network_type:
out['provider:network_type'] = self.network_type
if self.physical_network:
out['provider:physical_network'] = self.physical_network
if self.segmentation_id:
out['provider:segmentation_id'] = self.segmentation_id
if self.external:
out['router:external'] = self.external
return {'network': out}
class NetworkSettingsError(Exception):
"""
Exception to be thrown when networks settings attributes are incorrect
"""
class SubnetSettings:
"""
Class representing a subnet configuration
"""
def __init__(self, **kwargs):
"""
Constructor - all parameters are optional except cidr (subnet mask)
:param name: The subnet name (required)
:param cidr: The CIDR (required)
:param ip_version: The IP version, which is 4 or 6 (required)
:param project_name: The name of the project who owns the network.
Only administrative users can specify a project ID
other than their own. You cannot change this value
through authorization policies (optional)
:param start: The start address for the allocation pools (optional)
:param end: The end address for the allocation pools (optional)
:param gateway_ip: The gateway IP address (optional)
:param enable_dhcp: Set to true if DHCP is enabled and false if DHCP is
disabled (optional)
:param dns_nameservers: A list of DNS name servers for the subnet.
Specify each name server as an IP address
and separate multiple entries with a space.
For example [8.8.8.7 8.8.8.8]
(default '8.8.8.8')
:param host_routes: A list of host route dictionaries for the subnet.
For example:
"host_routes":[
{
"destination":"0.0.0.0/0",
"nexthop":"123.456.78.9"
},
{
"destination":"192.168.0.0/24",
"nexthop":"192.168.0.1"
}
]
:param destination: The destination for static route (optional)
:param nexthop: The next hop for the destination (optional)
:param ipv6_ra_mode: A valid value is dhcpv6-stateful,
dhcpv6-stateless, or slaac (optional)
:param ipv6_address_mode: A valid value is dhcpv6-stateful,
dhcpv6-stateless, or slaac (optional)
:raise: SubnetSettingsError when config does not have or cidr values
are None
"""
self.cidr = kwargs.get('cidr')
if kwargs.get('ip_version'):
self.ip_version = kwargs['ip_version']
else:
self.ip_version = 4
# Optional attributes that can be set after instantiation
self.name = kwargs.get('name')
self.project_name = kwargs.get('project_name')
self.start = kwargs.get('start')
self.end = kwargs.get('end')
self.gateway_ip = kwargs.get('gateway_ip')
self.enable_dhcp = kwargs.get('enable_dhcp')
if kwargs.get('dns_nameservers'):
self.dns_nameservers = kwargs.get('dns_nameservers')
else:
self.dns_nameservers = ['8.8.8.8']
self.host_routes = kwargs.get('host_routes')
self.destination = kwargs.get('destination')
self.nexthop = kwargs.get('nexthop')
self.ipv6_ra_mode = kwargs.get('ipv6_ra_mode')
self.ipv6_address_mode = kwargs.get('ipv6_address_mode')
if not self.name or not self.cidr:
raise SubnetSettingsError('Name and cidr required for subnets')
def dict_for_neutron(self, os_creds, network=None):
"""
Returns a dictionary object representing this object.
This is meant to be converted into JSON designed for use by the Neutron
API
:param os_creds: the OpenStack credentials
:param network: The network object on which the subnet will be created
(optional)
:return: the dictionary object
"""
out = {
'cidr': self.cidr,
'ip_version': self.ip_version,
}
if network:
out['network_id'] = network.id
if self.name:
out['name'] = self.name
if self.project_name:
keystone = keystone_utils.keystone_client(os_creds)
project = keystone_utils.get_project(
keystone=keystone, project_name=self.project_name)
project_id = None
if project:
project_id = project.id
if project_id:
out['tenant_id'] = project_id
else:
raise SubnetSettingsError(
'Could not find project ID for project named - ' +
self.project_name)
if self.start and self.end:
out['allocation_pools'] = [{'start': self.start, 'end': self.end}]
if self.gateway_ip:
out['gateway_ip'] = self.gateway_ip
if self.enable_dhcp is not None:
out['enable_dhcp'] = self.enable_dhcp
if self.dns_nameservers and len(self.dns_nameservers) > 0:
out['dns_nameservers'] = self.dns_nameservers
if self.host_routes and len(self.host_routes) > 0:
out['host_routes'] = self.host_routes
if self.destination:
out['destination'] = self.destination
if self.nexthop:
out['nexthop'] = self.nexthop
if self.ipv6_ra_mode:
out['ipv6_ra_mode'] = self.ipv6_ra_mode
if self.ipv6_address_mode:
out['ipv6_address_mode'] = self.ipv6_address_mode
return out
class SubnetSettingsError(Exception):
"""
Exception to be thrown when subnet settings attributes are incorrect
"""
class PortSettings:
"""
Class representing a port configuration
"""
def __init__(self, **kwargs):
"""
Constructor
:param name: A symbolic name for the port (optional).
:param network_name: The name of the network on which to create the
port (required).
:param admin_state_up: A boolean value denoting the administrative
status of the port (default = True)
:param project_name: The name of the project who owns the network.
Only administrative users can specify a project ID
other than their own. You cannot change this value
through authorization policies (optional)
:param mac_address: The MAC address. If you specify an address that is
not valid, a Bad Request (400) status code is
returned. If you do not specify a MAC address,
OpenStack Networking tries to allocate one. If a
failure occurs, a Service Unavailable (503) status
code is returned (optional)
:param ip_addrs: A list of dict objects where each contains two keys
'subnet_name' and 'ip' values which will get mapped to
self.fixed_ips. These values will be directly
translated into the fixed_ips dict (optional)
:param fixed_ips: A dict where the key is the subnet IDs and value is
the IP address to assign to the port (optional and
recommended to configure via ip_addrs instead)
:param security_groups: One or more security group IDs.
:param allowed_address_pairs: A dictionary containing a set of zero or
more allowed address pairs. An address
pair contains an IP address and MAC
address (optional)
:param opt_value: The extra DHCP option value (optional)
:param opt_name: The extra DHCP option name (optional)
:param device_owner: The ID of the entity that uses this port.
For example, a DHCP agent (optional)
:param device_id: The ID of the device that uses this port.
For example, a virtual server (optional)
:return:
"""
if 'port' in kwargs:
kwargs = kwargs['port']
self.network = None
self.name = kwargs.get('name')
self.network_name = kwargs.get('network_name')
if kwargs.get('admin_state_up') is not None:
self.admin_state_up = bool(kwargs['admin_state_up'])
else:
self.admin_state_up = True
self.project_name = kwargs.get('project_name')
self.mac_address = kwargs.get('mac_address')
self.ip_addrs = kwargs.get('ip_addrs')
self.fixed_ips = kwargs.get('fixed_ips')
self.security_groups = kwargs.get('security_groups')
self.allowed_address_pairs = kwargs.get('allowed_address_pairs')
self.opt_value = kwargs.get('opt_value')
self.opt_name = kwargs.get('opt_name')
self.device_owner = kwargs.get('device_owner')
self.device_id = kwargs.get('device_id')
if not self.network_name:
raise PortSettingsError(
'The attribute network_name is required')
def __set_fixed_ips(self, neutron):
"""
Sets the self.fixed_ips value
:param neutron: the Neutron client
:return: None
"""
if not self.fixed_ips and self.ip_addrs:
self.fixed_ips = list()
for ip_addr_dict in self.ip_addrs:
subnet = neutron_utils.get_subnet(
neutron, subnet_name=ip_addr_dict['subnet_name'])
if subnet and 'ip' in ip_addr_dict:
self.fixed_ips.append({'ip_address': ip_addr_dict['ip'],
'subnet_id': subnet.id})
else:
raise PortSettingsError(
'Invalid port configuration, subnet does not exist '
'with name - ' + ip_addr_dict['subnet_name'])
def dict_for_neutron(self, neutron, os_creds):
"""
Returns a dictionary object representing this object.
This is meant to be converted into JSON designed for use by the Neutron
API
TODO - expand automated testing to exercise all parameters
:param neutron: the Neutron client
:param os_creds: the OpenStack credentials
:return: the dictionary object
"""
self.__set_fixed_ips(neutron)
out = dict()
project_id = None
if self.project_name:
keystone = keystone_utils.keystone_client(os_creds)
project = keystone_utils.get_project(
keystone=keystone, project_name=self.project_name)
if project:
project_id = project.id
if not self.network:
self.network = neutron_utils.get_network(
neutron, network_name=self.network_name, project_id=project_id)
if not self.network:
raise PortSettingsError(
'Cannot locate network with name - ' + self.network_name)
out['network_id'] = self.network.id
if self.admin_state_up is not None:
out['admin_state_up'] = self.admin_state_up
if self.name:
out['name'] = self.name
if self.project_name:
if project_id:
out['tenant_id'] = project_id
else:
raise PortSettingsError(
'Could not find project ID for project named - ' +
self.project_name)
if self.mac_address:
out['mac_address'] = self.mac_address
if self.fixed_ips and len(self.fixed_ips) > 0:
out['fixed_ips'] = self.fixed_ips
if self.security_groups:
out['security_groups'] = self.security_groups
if self.allowed_address_pairs and len(self.allowed_address_pairs) > 0:
out['allowed_address_pairs'] = self.allowed_address_pairs
if self.opt_value:
out['opt_value'] = self.opt_value
if self.opt_name:
out['opt_name'] = self.opt_name
if self.device_owner:
out['device_owner'] = self.device_owner
if self.device_id:
out['device_id'] = self.device_id
return {'port': out}
def __eq__(self, other):
return (self.name == other.name and
self.network_name == other.network_name and
self.admin_state_up == other.admin_state_up and
self.project_name == other.project_name and
self.mac_address == other.mac_address and
self.ip_addrs == other.ip_addrs and
self.fixed_ips == other.fixed_ips and
self.security_groups == other.security_groups and
self.allowed_address_pairs == other.allowed_address_pairs and
self.opt_value == other.opt_value and
self.opt_name == other.opt_name and
self.device_owner == other.device_owner and
self.device_id == other.device_id)
class PortSettingsError(Exception):
"""
Exception to be thrown when port settings attributes are incorrect
"""
|