/
_network.py
2557 lines (2145 loc) · 102 KB
/
_network.py
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# 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 types so that we can reference ListType in sphinx param declarations.
# We can't just use list, because sphinx gets confused by
# openstack.resource.Resource.list and openstack.resource2.Resource.list
import time
import threading
import types # noqa
from openstack.cloud import exc
from openstack.cloud import _normalize
from openstack.cloud import _utils
from openstack import exceptions
from openstack import proxy
class NetworkCloudMixin(_normalize.Normalizer):
def __init__(self):
self._ports = None
self._ports_time = 0
self._ports_lock = threading.Lock()
@_utils.cache_on_arguments()
def _neutron_extensions(self):
extensions = set()
resp = self.network.get('/extensions.json')
data = proxy._json_response(
resp,
error_message="Error fetching extension list for neutron")
for extension in self._get_and_munchify('extensions', data):
extensions.add(extension['alias'])
return extensions
def _has_neutron_extension(self, extension_alias):
return extension_alias in self._neutron_extensions()
def search_networks(self, name_or_id=None, filters=None):
"""Search networks
:param name_or_id: Name or ID of the desired network.
:param filters: a dict containing additional filters to use. e.g.
{'router:external': True}
:returns: a list of ``munch.Munch`` containing the network description.
:raises: ``OpenStackCloudException`` if something goes wrong during the
OpenStack API call.
"""
networks = self.list_networks(
filters if isinstance(filters, dict) else None)
return _utils._filter_list(networks, name_or_id, filters)
def search_routers(self, name_or_id=None, filters=None):
"""Search routers
:param name_or_id: Name or ID of the desired router.
:param filters: a dict containing additional filters to use. e.g.
{'admin_state_up': True}
:returns: a list of ``munch.Munch`` containing the router description.
:raises: ``OpenStackCloudException`` if something goes wrong during the
OpenStack API call.
"""
routers = self.list_routers(
filters if isinstance(filters, dict) else None)
return _utils._filter_list(routers, name_or_id, filters)
def search_subnets(self, name_or_id=None, filters=None):
"""Search subnets
:param name_or_id: Name or ID of the desired subnet.
:param filters: a dict containing additional filters to use. e.g.
{'enable_dhcp': True}
:returns: a list of ``munch.Munch`` containing the subnet description.
:raises: ``OpenStackCloudException`` if something goes wrong during the
OpenStack API call.
"""
subnets = self.list_subnets(
filters if isinstance(filters, dict) else None)
return _utils._filter_list(subnets, name_or_id, filters)
def search_ports(self, name_or_id=None, filters=None):
"""Search ports
:param name_or_id: Name or ID of the desired port.
:param filters: a dict containing additional filters to use. e.g.
{'device_id': '2711c67a-b4a7-43dd-ace7-6187b791c3f0'}
:returns: a list of ``munch.Munch`` containing the port description.
:raises: ``OpenStackCloudException`` if something goes wrong during the
OpenStack API call.
"""
# If port caching is enabled, do not push the filter down to
# neutron; get all the ports (potentially from the cache) and
# filter locally.
if self._PORT_AGE or isinstance(filters, str):
pushdown_filters = None
else:
pushdown_filters = filters
ports = self.list_ports(pushdown_filters)
return _utils._filter_list(ports, name_or_id, filters)
def list_networks(self, filters=None):
"""List all available networks.
:param filters: (optional) dict of filter conditions to push down
:returns: A list of ``munch.Munch`` containing network info.
"""
# If the cloud is running nova-network, just return an empty list.
if not self.has_service('network'):
return []
# Translate None from search interface to empty {} for kwargs below
if not filters:
filters = {}
data = self.network.get("/networks.json", params=filters)
return self._get_and_munchify('networks', data)
def list_routers(self, filters=None):
"""List all available routers.
:param filters: (optional) dict of filter conditions to push down
:returns: A list of router ``munch.Munch``.
"""
# If the cloud is running nova-network, just return an empty list.
if not self.has_service('network'):
return []
# Translate None from search interface to empty {} for kwargs below
if not filters:
filters = {}
resp = self.network.get("/routers.json", params=filters)
data = proxy._json_response(
resp,
error_message="Error fetching router list")
return self._get_and_munchify('routers', data)
def list_subnets(self, filters=None):
"""List all available subnets.
:param filters: (optional) dict of filter conditions to push down
:returns: A list of subnet ``munch.Munch``.
"""
# If the cloud is running nova-network, just return an empty list.
if not self.has_service('network'):
return []
# Translate None from search interface to empty {} for kwargs below
if not filters:
filters = {}
data = self.network.get("/subnets.json", params=filters)
return self._get_and_munchify('subnets', data)
def list_ports(self, filters=None):
"""List all available ports.
:param filters: (optional) dict of filter conditions to push down
:returns: A list of port ``munch.Munch``.
"""
# If pushdown filters are specified and we do not have batched caching
# enabled, bypass local caching and push down the filters.
if filters and self._PORT_AGE == 0:
return self._list_ports(filters)
if (time.time() - self._ports_time) >= self._PORT_AGE:
# Since we're using cached data anyway, we don't need to
# have more than one thread actually submit the list
# ports task. Let the first one submit it while holding
# a lock, and the non-blocking acquire method will cause
# subsequent threads to just skip this and use the old
# data until it succeeds.
# Initially when we never got data, block to retrieve some data.
first_run = self._ports is None
if self._ports_lock.acquire(first_run):
try:
if not (first_run and self._ports is not None):
self._ports = self._list_ports({})
self._ports_time = time.time()
finally:
self._ports_lock.release()
# Wrap the return with filter_list so that if filters were passed
# but we were batching/caching and thus always fetching the whole
# list from the cloud, we still return a filtered list.
return _utils._filter_list(self._ports, None, filters or {})
def _list_ports(self, filters):
# If the cloud is running nova-network, just return an empty list.
if not self.has_service('network'):
return []
resp = self.network.get("/ports.json", params=filters)
data = proxy._json_response(
resp,
error_message="Error fetching port list")
return self._get_and_munchify('ports', data)
def get_qos_policy(self, name_or_id, filters=None):
"""Get a QoS policy by name or ID.
:param name_or_id: Name or ID of the policy.
:param filters:
A dictionary of meta data to use for further filtering. Elements
of this dictionary may, themselves, be dictionaries. Example::
{
'last_name': 'Smith',
'other': {
'gender': 'Female'
}
}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A policy ``munch.Munch`` or None if no matching network is
found.
"""
return _utils._get_entity(
self, 'qos_policie', name_or_id, filters)
def search_qos_policies(self, name_or_id=None, filters=None):
"""Search QoS policies
:param name_or_id: Name or ID of the desired policy.
:param filters: a dict containing additional filters to use. e.g.
{'shared': True}
:returns: a list of ``munch.Munch`` containing the network description.
:raises: ``OpenStackCloudException`` if something goes wrong during the
OpenStack API call.
"""
policies = self.list_qos_policies(filters)
return _utils._filter_list(policies, name_or_id, filters)
def list_qos_rule_types(self, filters=None):
"""List all available QoS rule types.
:param filters: (optional) dict of filter conditions to push down
:returns: A list of rule types ``munch.Munch``.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud')
# Translate None from search interface to empty {} for kwargs below
if not filters:
filters = {}
resp = self.network.get("/qos/rule-types.json", params=filters)
data = proxy._json_response(
resp,
error_message="Error fetching QoS rule types list")
return self._get_and_munchify('rule_types', data)
def get_qos_rule_type_details(self, rule_type, filters=None):
"""Get a QoS rule type details by rule type name.
:param string rule_type: Name of the QoS rule type.
:returns: A rule type details ``munch.Munch`` or None if
no matching rule type is found.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud')
if not self._has_neutron_extension('qos-rule-type-details'):
raise exc.OpenStackCloudUnavailableExtension(
'qos-rule-type-details extension is not available '
'on target cloud')
resp = self.network.get(
"/qos/rule-types/{rule_type}.json".format(rule_type=rule_type))
data = proxy._json_response(
resp,
error_message="Error fetching QoS details of {rule_type} "
"rule type".format(rule_type=rule_type))
return self._get_and_munchify('rule_type', data)
def list_qos_policies(self, filters=None):
"""List all available QoS policies.
:param filters: (optional) dict of filter conditions to push down
:returns: A list of policies ``munch.Munch``.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud')
# Translate None from search interface to empty {} for kwargs below
if not filters:
filters = {}
resp = self.network.get("/qos/policies.json", params=filters)
data = proxy._json_response(
resp,
error_message="Error fetching QoS policies list")
return self._get_and_munchify('policies', data)
def get_network(self, name_or_id, filters=None):
"""Get a network by name or ID.
:param name_or_id: Name or ID of the network.
:param filters:
A dictionary of meta data to use for further filtering. Elements
of this dictionary may, themselves, be dictionaries. Example::
{
'last_name': 'Smith',
'other': {
'gender': 'Female'
}
}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A network ``munch.Munch`` or None if no matching network is
found.
"""
return _utils._get_entity(self, 'network', name_or_id, filters)
def get_network_by_id(self, id):
""" Get a network by ID
:param id: ID of the network.
:returns: A network ``munch.Munch``.
"""
resp = self.network.get('/networks/{id}'.format(id=id))
data = proxy._json_response(
resp,
error_message="Error getting network with ID {id}".format(id=id)
)
network = self._get_and_munchify('network', data)
return network
def get_router(self, name_or_id, filters=None):
"""Get a router by name or ID.
:param name_or_id: Name or ID of the router.
:param filters:
A dictionary of meta data to use for further filtering. Elements
of this dictionary may, themselves, be dictionaries. Example::
{
'last_name': 'Smith',
'other': {
'gender': 'Female'
}
}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A router ``munch.Munch`` or None if no matching router is
found.
"""
return _utils._get_entity(self, 'router', name_or_id, filters)
def get_subnet(self, name_or_id, filters=None):
"""Get a subnet by name or ID.
:param name_or_id: Name or ID of the subnet.
:param filters:
A dictionary of meta data to use for further filtering. Elements
of this dictionary may, themselves, be dictionaries. Example::
{
'last_name': 'Smith',
'other': {
'gender': 'Female'
}
}
:returns: A subnet ``munch.Munch`` or None if no matching subnet is
found.
"""
return _utils._get_entity(self, 'subnet', name_or_id, filters)
def get_subnet_by_id(self, id):
""" Get a subnet by ID
:param id: ID of the subnet.
:returns: A subnet ``munch.Munch``.
"""
resp = self.network.get('/subnets/{id}'.format(id=id))
data = proxy._json_response(
resp,
error_message="Error getting subnet with ID {id}".format(id=id)
)
subnet = self._get_and_munchify('subnet', data)
return subnet
def get_port(self, name_or_id, filters=None):
"""Get a port by name or ID.
:param name_or_id: Name or ID of the port.
:param filters:
A dictionary of meta data to use for further filtering. Elements
of this dictionary may, themselves, be dictionaries. Example::
{
'last_name': 'Smith',
'other': {
'gender': 'Female'
}
}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A port ``munch.Munch`` or None if no matching port is found.
"""
return _utils._get_entity(self, 'port', name_or_id, filters)
def get_port_by_id(self, id):
""" Get a port by ID
:param id: ID of the port.
:returns: A port ``munch.Munch``.
"""
resp = self.network.get('/ports/{id}'.format(id=id))
data = proxy._json_response(
resp,
error_message="Error getting port with ID {id}".format(id=id)
)
port = self._get_and_munchify('port', data)
return port
def create_network(self, name, shared=False, admin_state_up=True,
external=False, provider=None, project_id=None,
availability_zone_hints=None,
port_security_enabled=None,
mtu_size=None, dns_domain=None):
"""Create a network.
:param string name: Name of the network being created.
:param bool shared: Set the network as shared.
:param bool admin_state_up: Set the network administrative state to up.
:param bool external: Whether this network is externally accessible.
:param dict provider: A dict of network provider options. Example::
{ 'network_type': 'vlan', 'segmentation_id': 'vlan1' }
:param string project_id: Specify the project ID this network
will be created on (admin-only).
:param types.ListType availability_zone_hints: A list of availability
zone hints.
:param bool port_security_enabled: Enable / Disable port security
:param int mtu_size: maximum transmission unit value to address
fragmentation. Minimum value is 68 for IPv4, and 1280 for IPv6.
:param string dns_domain: Specify the DNS domain associated with
this network.
:returns: The network object.
:raises: OpenStackCloudException on operation error.
"""
network = {
'name': name,
'admin_state_up': admin_state_up,
}
if shared:
network['shared'] = shared
if project_id is not None:
network['tenant_id'] = project_id
if availability_zone_hints is not None:
if not isinstance(availability_zone_hints, list):
raise exc.OpenStackCloudException(
"Parameter 'availability_zone_hints' must be a list")
if not self._has_neutron_extension('network_availability_zone'):
raise exc.OpenStackCloudUnavailableExtension(
'network_availability_zone extension is not available on '
'target cloud')
network['availability_zone_hints'] = availability_zone_hints
if provider:
if not isinstance(provider, dict):
raise exc.OpenStackCloudException(
"Parameter 'provider' must be a dict")
# Only pass what we know
for attr in ('physical_network', 'network_type',
'segmentation_id'):
if attr in provider:
arg = "provider:" + attr
network[arg] = provider[attr]
# Do not send 'router:external' unless it is explicitly
# set since sending it *might* cause "Forbidden" errors in
# some situations. It defaults to False in the client, anyway.
if external:
network['router:external'] = True
if port_security_enabled is not None:
if not isinstance(port_security_enabled, bool):
raise exc.OpenStackCloudException(
"Parameter 'port_security_enabled' must be a bool")
network['port_security_enabled'] = port_security_enabled
if mtu_size:
if not isinstance(mtu_size, int):
raise exc.OpenStackCloudException(
"Parameter 'mtu_size' must be an integer.")
if not mtu_size >= 68:
raise exc.OpenStackCloudException(
"Parameter 'mtu_size' must be greater than 67.")
network['mtu'] = mtu_size
if dns_domain:
network['dns_domain'] = dns_domain
data = self.network.post("/networks.json", json={'network': network})
# Reset cache so the new network is picked up
self._reset_network_caches()
return self._get_and_munchify('network', data)
@_utils.valid_kwargs("name", "shared", "admin_state_up", "external",
"provider", "mtu_size", "port_security_enabled",
"dns_domain")
def update_network(self, name_or_id, **kwargs):
"""Update a network.
:param string name_or_id: Name or ID of the network being updated.
:param string name: New name of the network.
:param bool shared: Set the network as shared.
:param bool admin_state_up: Set the network administrative state to up.
:param bool external: Whether this network is externally accessible.
:param dict provider: A dict of network provider options. Example::
{ 'network_type': 'vlan', 'segmentation_id': 'vlan1' }
:param int mtu_size: New maximum transmission unit value to address
fragmentation. Minimum value is 68 for IPv4, and 1280 for IPv6.
:param bool port_security_enabled: Enable or disable port security.
:param string dns_domain: Specify the DNS domain associated with
this network.
:returns: The updated network object.
:raises: OpenStackCloudException on operation error.
"""
if 'provider' in kwargs:
if not isinstance(kwargs['provider'], dict):
raise exc.OpenStackCloudException(
"Parameter 'provider' must be a dict")
# Only pass what we know
provider = {}
for key in kwargs['provider']:
if key in ('physical_network', 'network_type',
'segmentation_id'):
provider['provider:' + key] = kwargs['provider'][key]
kwargs['provider'] = provider
if 'external' in kwargs:
kwargs['router:external'] = kwargs.pop('external')
if 'port_security_enabled' in kwargs:
if not isinstance(kwargs['port_security_enabled'], bool):
raise exc.OpenStackCloudException(
"Parameter 'port_security_enabled' must be a bool")
if 'mtu_size' in kwargs:
if not isinstance(kwargs['mtu_size'], int):
raise exc.OpenStackCloudException(
"Parameter 'mtu_size' must be an integer.")
if kwargs['mtu_size'] < 68:
raise exc.OpenStackCloudException(
"Parameter 'mtu_size' must be greater than 67.")
kwargs['mtu'] = kwargs.pop('mtu_size')
network = self.get_network(name_or_id)
if not network:
raise exc.OpenStackCloudException(
"Network %s not found." % name_or_id)
data = proxy._json_response(self.network.put(
"/networks/{net_id}.json".format(net_id=network.id),
json={"network": kwargs}),
error_message="Error updating network {0}".format(name_or_id))
self._reset_network_caches()
return self._get_and_munchify('network', data)
def delete_network(self, name_or_id):
"""Delete a network.
:param name_or_id: Name or ID of the network being deleted.
:returns: True if delete succeeded, False otherwise.
:raises: OpenStackCloudException on operation error.
"""
network = self.get_network(name_or_id)
if not network:
self.log.debug("Network %s not found for deleting", name_or_id)
return False
exceptions.raise_from_response(self.network.delete(
"/networks/{network_id}.json".format(network_id=network['id'])))
# Reset cache so the deleted network is removed
self._reset_network_caches()
return True
def set_network_quotas(self, name_or_id, **kwargs):
""" Set a network quota in a project
:param name_or_id: project name or id
:param kwargs: key/value pairs of quota name and quota value
:raises: OpenStackCloudException if the resource to set the
quota does not exist.
"""
proj = self.get_project(name_or_id)
if not proj:
raise exc.OpenStackCloudException("project does not exist")
exceptions.raise_from_response(
self.network.put(
'/quotas/{project_id}.json'.format(project_id=proj.id),
json={'quota': kwargs}),
error_message=("Error setting Neutron's quota for "
"project {0}".format(proj.id)))
def get_network_quotas(self, name_or_id, details=False):
""" Get network quotas for a project
:param name_or_id: project name or id
:param details: if set to True it will return details about usage
of quotas by given project
:raises: OpenStackCloudException if it's not a valid project
:returns: Munch object with the quotas
"""
proj = self.get_project(name_or_id)
if not proj:
raise exc.OpenStackCloudException("project does not exist")
url = '/quotas/{project_id}'.format(project_id=proj.id)
if details:
url = url + "/details"
url = url + ".json"
data = proxy._json_response(
self.network.get(url),
error_message=("Error fetching Neutron's quota for "
"project {0}".format(proj.id)))
return self._get_and_munchify('quota', data)
def get_network_extensions(self):
"""Get Cloud provided network extensions
:returns: set of Neutron extension aliases
"""
return self._neutron_extensions()
def delete_network_quotas(self, name_or_id):
""" Delete network quotas for a project
:param name_or_id: project name or id
:raises: OpenStackCloudException if it's not a valid project or the
network client call failed
:returns: dict with the quotas
"""
proj = self.get_project(name_or_id)
if not proj:
raise exc.OpenStackCloudException("project does not exist")
exceptions.raise_from_response(
self.network.delete(
'/quotas/{project_id}.json'.format(project_id=proj.id)),
error_message=("Error deleting Neutron's quota for "
"project {0}".format(proj.id)))
@_utils.valid_kwargs(
'action', 'description', 'destination_firewall_group_id',
'destination_ip_address', 'destination_port', 'enabled', 'ip_version',
'name', 'project_id', 'protocol', 'shared', 'source_firewall_group_id',
'source_ip_address', 'source_port')
def create_firewall_rule(self, **kwargs):
"""
Creates firewall rule.
:param action: Action performed on traffic.
Valid values: allow, deny
Defaults to deny.
:param description: Human-readable description.
:param destination_firewall_group_id: ID of destination firewall group.
:param destination_ip_address: IPv4-, IPv6 address or CIDR.
:param destination_port: Port or port range (e.g. 80:90)
:param bool enabled: Status of firewall rule. You can disable rules
without disassociating them from firewall
policies. Defaults to True.
:param int ip_version: IP Version.
Valid values: 4, 6
Defaults to 4.
:param name: Human-readable name.
:param project_id: Project id.
:param protocol: IP protocol.
Valid values: icmp, tcp, udp, null
:param bool shared: Visibility to other projects.
Defaults to False.
:param source_firewall_group_id: ID of source firewall group.
:param source_ip_address: IPv4-, IPv6 address or CIDR.
:param source_port: Port or port range (e.g. 80:90)
:raises: BadRequestException if parameters are malformed
:return: created firewall rule
:rtype: FirewallRule
"""
return self.network.create_firewall_rule(**kwargs)
def delete_firewall_rule(self, name_or_id, filters=None):
"""
Deletes firewall rule.
Prints debug message in case to-be-deleted resource was not found.
:param name_or_id: firewall rule name or id
:param dict filters: optional filters
:raises: DuplicateResource on multiple matches
:return: True if resource is successfully deleted, False otherwise.
:rtype: bool
"""
if not filters:
filters = {}
try:
firewall_rule = self.network.find_firewall_rule(
name_or_id, ignore_missing=False, **filters)
self.network.delete_firewall_rule(firewall_rule,
ignore_missing=False)
except exceptions.ResourceNotFound:
self.log.debug('Firewall rule %s not found for deleting',
name_or_id)
return False
return True
def get_firewall_rule(self, name_or_id, filters=None):
"""
Retrieves a single firewall rule.
:param name_or_id: firewall rule name or id
:param dict filters: optional filters
:raises: DuplicateResource on multiple matches
:return: firewall rule dict or None if not found
:rtype: FirewallRule
"""
if not filters:
filters = {}
return self.network.find_firewall_rule(name_or_id, **filters)
def list_firewall_rules(self, filters=None):
"""
Lists firewall rules.
:param dict filters: optional filters
:return: list of firewall rules
:rtype: list[FirewallRule]
"""
if not filters:
filters = {}
return list(self.network.firewall_rules(**filters))
@_utils.valid_kwargs(
'action', 'description', 'destination_firewall_group_id',
'destination_ip_address', 'destination_port', 'enabled', 'ip_version',
'name', 'project_id', 'protocol', 'shared', 'source_firewall_group_id',
'source_ip_address', 'source_port')
def update_firewall_rule(self, name_or_id, filters=None, **kwargs):
"""
Updates firewall rule.
:param name_or_id: firewall rule name or id
:param dict filters: optional filters
:param kwargs: firewall rule update parameters.
See create_firewall_rule docstring for valid parameters.
:raises: BadRequestException if parameters are malformed
:raises: NotFoundException if resource is not found
:return: updated firewall rule
:rtype: FirewallRule
"""
if not filters:
filters = {}
firewall_rule = self.network.find_firewall_rule(
name_or_id, ignore_missing=False, **filters)
return self.network.update_firewall_rule(firewall_rule, **kwargs)
def _get_firewall_rule_ids(self, name_or_id_list, filters=None):
"""
Takes a list of firewall rule name or ids, looks them up and returns
a list of firewall rule ids.
Used by `create_firewall_policy` and `update_firewall_policy`.
:param list[str] name_or_id_list: firewall rule name or id list
:param dict filters: optional filters
:raises: DuplicateResource on multiple matches
:raises: NotFoundException if resource is not found
:return: list of firewall rule ids
:rtype: list[str]
"""
if not filters:
filters = {}
ids_list = []
for name_or_id in name_or_id_list:
ids_list.append(self.network.find_firewall_rule(
name_or_id, ignore_missing=False, **filters)['id'])
return ids_list
@_utils.valid_kwargs('audited', 'description', 'firewall_rules', 'name',
'project_id', 'shared')
def create_firewall_policy(self, **kwargs):
"""
Create firewall policy.
:param bool audited: Status of audition of firewall policy.
Set to False each time the firewall policy or the
associated firewall rules are changed.
Has to be explicitly set to True.
:param description: Human-readable description.
:param list[str] firewall_rules: List of associated firewall rules.
:param name: Human-readable name.
:param project_id: Project id.
:param bool shared: Visibility to other projects.
Defaults to False.
:raises: BadRequestException if parameters are malformed
:raises: ResourceNotFound if a resource from firewall_list not found
:return: created firewall policy
:rtype: FirewallPolicy
"""
if 'firewall_rules' in kwargs:
kwargs['firewall_rules'] = self._get_firewall_rule_ids(
kwargs['firewall_rules'])
return self.network.create_firewall_policy(**kwargs)
def delete_firewall_policy(self, name_or_id, filters=None):
"""
Deletes firewall policy.
Prints debug message in case to-be-deleted resource was not found.
:param name_or_id: firewall policy name or id
:param dict filters: optional filters
:raises: DuplicateResource on multiple matches
:return: True if resource is successfully deleted, False otherwise.
:rtype: bool
"""
if not filters:
filters = {}
try:
firewall_policy = self.network.find_firewall_policy(
name_or_id, ignore_missing=False, **filters)
self.network.delete_firewall_policy(firewall_policy,
ignore_missing=False)
except exceptions.ResourceNotFound:
self.log.debug('Firewall policy %s not found for deleting',
name_or_id)
return False
return True
def get_firewall_policy(self, name_or_id, filters=None):
"""
Retrieves a single firewall policy.
:param name_or_id: firewall policy name or id
:param dict filters: optional filters
:raises: DuplicateResource on multiple matches
:return: firewall policy or None if not found
:rtype: FirewallPolicy
"""
if not filters:
filters = {}
return self.network.find_firewall_policy(name_or_id, **filters)
def list_firewall_policies(self, filters=None):
"""
Lists firewall policies.
:param dict filters: optional filters
:return: list of firewall policies
:rtype: list[FirewallPolicy]
"""
if not filters:
filters = {}
return list(self.network.firewall_policies(**filters))
@_utils.valid_kwargs('audited', 'description', 'firewall_rules', 'name',
'project_id', 'shared')
def update_firewall_policy(self, name_or_id, filters=None, **kwargs):
"""
Updates firewall policy.
:param name_or_id: firewall policy name or id
:param dict filters: optional filters
:param kwargs: firewall policy update parameters
See create_firewall_policy docstring for valid parameters.
:raises: BadRequestException if parameters are malformed
:raises: DuplicateResource on multiple matches
:raises: ResourceNotFound if resource is not found
:return: updated firewall policy
:rtype: FirewallPolicy
"""
if not filters:
filters = {}
firewall_policy = self.network.find_firewall_policy(
name_or_id, ignore_missing=False, **filters)
if 'firewall_rules' in kwargs:
kwargs['firewall_rules'] = self._get_firewall_rule_ids(
kwargs['firewall_rules'])
return self.network.update_firewall_policy(firewall_policy, **kwargs)
def insert_rule_into_policy(self, name_or_id, rule_name_or_id,
insert_after=None, insert_before=None,
filters=None):
"""
Adds firewall rule to the firewall_rules list of a firewall policy.
Short-circuits and returns the firewall policy early if the firewall
rule id is already present in the firewall_rules list.
This method doesn't do re-ordering. If you want to move a firewall rule
or down the list, you have to remove and re-add it.
:param name_or_id: firewall policy name or id
:param rule_name_or_id: firewall rule name or id
:param insert_after: rule name or id that should precede added rule
:param insert_before: rule name or id that should succeed added rule
:param dict filters: optional filters
:raises: DuplicateResource on multiple matches
:raises: ResourceNotFound if firewall policy or any of the firewall
rules (inserted, after, before) is not found.
:return: updated firewall policy
:rtype: FirewallPolicy
"""
if not filters:
filters = {}
firewall_policy = self.network.find_firewall_policy(
name_or_id, ignore_missing=False, **filters)
firewall_rule = self.network.find_firewall_rule(
rule_name_or_id, ignore_missing=False)
# short-circuit if rule already in firewall_rules list
# the API can't do any re-ordering of existing rules
if firewall_rule['id'] in firewall_policy['firewall_rules']:
self.log.debug(
'Firewall rule %s already associated with firewall policy %s',
rule_name_or_id, name_or_id)
return firewall_policy
pos_params = {}
if insert_after is not None:
pos_params['insert_after'] = self.network.find_firewall_rule(
insert_after, ignore_missing=False)['id']
if insert_before is not None:
pos_params['insert_before'] = self.network.find_firewall_rule(
insert_before, ignore_missing=False)['id']
return self.network.insert_rule_into_policy(firewall_policy['id'],
firewall_rule['id'],
**pos_params)
def remove_rule_from_policy(self, name_or_id, rule_name_or_id,
filters=None):
"""
Remove firewall rule from firewall policy's firewall_rules list.
Short-circuits and returns firewall policy early if firewall rule
is already absent from the firewall_rules list.
:param name_or_id: firewall policy name or id
:param rule_name_or_id: firewall rule name or id