-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
l3_db.py
2189 lines (1947 loc) · 101 KB
/
l3_db.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
# Copyright 2012 VMware, Inc. 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 functools
import random
import netaddr
from neutron_lib.api.definitions import l3 as l3_apidef
from neutron_lib.api.definitions import qos_fip as qos_fip_apidef
from neutron_lib.api import extensions
from neutron_lib.api import validators
from neutron_lib.callbacks import events
from neutron_lib.callbacks import exceptions
from neutron_lib.callbacks import registry
from neutron_lib.callbacks import resources
from neutron_lib import constants
from neutron_lib import context as n_ctx
from neutron_lib.db import api as db_api
from neutron_lib.db import model_query
from neutron_lib.db import resource_extend
from neutron_lib.db import utils as lib_db_utils
from neutron_lib import exceptions as n_exc
from neutron_lib.exceptions import l3 as l3_exc
from neutron_lib.plugins import constants as plugin_constants
from neutron_lib.plugins import directory
from neutron_lib.plugins import utils as plugin_utils
from neutron_lib import rpc as n_rpc
from neutron_lib.services import base as base_services
from neutron_lib.services.qos import constants as qos_const
from oslo_log import log as logging
from oslo_utils import uuidutils
from sqlalchemy import orm
from sqlalchemy.orm import exc
from neutron._i18n import _
from neutron.api.rpc.agentnotifiers import l3_rpc_agent_api
from neutron.common import ipv6_utils
from neutron.common import utils
from neutron.db import _utils as db_utils
from neutron.db.models import l3 as l3_models
from neutron.db.models import l3_attrs as l3_attrs_models
from neutron.db import models_v2
from neutron.db import standardattrdescription_db as st_attr
from neutron.extensions import l3
from neutron.extensions import segment as segment_ext
from neutron.objects import base as base_obj
from neutron.objects import port_forwarding
from neutron.objects import ports as port_obj
from neutron.objects import router as l3_obj
from neutron.objects import subnet as subnet_obj
from neutron import worker as neutron_worker
LOG = logging.getLogger(__name__)
DEVICE_OWNER_HA_REPLICATED_INT = constants.DEVICE_OWNER_HA_REPLICATED_INT
DEVICE_OWNER_ROUTER_INTF = constants.DEVICE_OWNER_ROUTER_INTF
DEVICE_OWNER_ROUTER_GW = constants.DEVICE_OWNER_ROUTER_GW
DEVICE_OWNER_FLOATINGIP = constants.DEVICE_OWNER_FLOATINGIP
EXTERNAL_GW_INFO = l3_apidef.EXTERNAL_GW_INFO
# Maps API field to DB column
# API parameter name and Database column names may differ.
# Useful to keep the filtering between API and Database.
API_TO_DB_COLUMN_MAP = {'port_id': 'fixed_port_id'}
CORE_ROUTER_ATTRS = ('id', 'name', 'tenant_id', 'admin_state_up', 'status')
FIP_ASSOC_MSG = ('Floating IP %(fip_id)s %(assoc)s. External IP: %(ext_ip)s, '
'port: %(port_id)s.')
@registry.has_registry_receivers
class L3_NAT_dbonly_mixin(l3.RouterPluginBase,
base_services.WorkerBase,
st_attr.StandardAttrDescriptionMixin):
"""Mixin class to add L3/NAT router methods to db_base_plugin_v2."""
router_device_owners = (
DEVICE_OWNER_HA_REPLICATED_INT,
DEVICE_OWNER_ROUTER_INTF,
DEVICE_OWNER_ROUTER_GW,
DEVICE_OWNER_FLOATINGIP
)
_dns_integration = None
_fip_qos = None
def __new__(cls, *args, **kwargs):
inst = super(L3_NAT_dbonly_mixin, cls).__new__(cls, *args, **kwargs)
inst._start_janitor()
return inst
@staticmethod
@registry.receives(resources.PORT, [events.BEFORE_DELETE])
def _prevent_l3_port_delete_callback(resource, event,
trigger, payload=None):
l3plugin = directory.get_plugin(plugin_constants.L3)
if l3plugin and payload.metadata['port_check']:
l3plugin.prevent_l3_port_deletion(
payload.context, payload.resource_id,
port=payload.metadata.get('port'))
@staticmethod
def _validate_subnet_address_mode(subnet):
if (subnet['ip_version'] == 6 and subnet['ipv6_ra_mode'] is None and
subnet['ipv6_address_mode'] is not None):
msg = (_('IPv6 subnet %s configured to receive RAs from an '
'external router cannot be added to Neutron Router.') %
subnet['id'])
raise n_exc.BadRequest(resource='router', msg=msg)
@property
def _is_dns_integration_supported(self):
if self._dns_integration is None:
self._dns_integration = (
extensions.is_extension_supported(
self._core_plugin, 'dns-integration') or
extensions.is_extension_supported(
self._core_plugin, 'dns-domain-ports'))
return self._dns_integration
@property
def _is_fip_qos_supported(self):
if self._fip_qos is None:
# Check L3 service plugin
self._fip_qos = extensions.is_extension_supported(
self, qos_fip_apidef.ALIAS)
return self._fip_qos
@property
def _core_plugin(self):
return directory.get_plugin()
def _start_janitor(self):
"""Starts the periodic job that cleans up broken complex resources.
This job will look for things like floating IP ports without an
associated floating IP and delete them 5 minutes after detection.
"""
interval = 60 * 5 # only every 5 minutes. cleanups should be rare
initial_delay = random.randint(0, interval) # splay multiple servers
janitor = neutron_worker.PeriodicWorker(self._clean_garbage, interval,
initial_delay)
self.add_worker(janitor)
def _clean_garbage(self):
if not hasattr(self, '_candidate_broken_fip_ports'):
self._candidate_broken_fip_ports = set()
context = n_ctx.get_admin_context()
candidates = self._get_dead_floating_port_candidates(context)
# just because a port is in 'candidates' doesn't necessarily mean
# it's broken, we could have just caught it before it was updated.
# We confirm by waiting until the next call of this function to see
# if it persists.
to_cleanup = candidates & self._candidate_broken_fip_ports
self._candidate_broken_fip_ports = candidates - to_cleanup
for port_id in to_cleanup:
# ensure it wasn't just a failure to update device_id before we
# delete it
try:
self._fix_or_kill_floating_port(context, port_id)
except Exception:
LOG.exception("Error cleaning up floating IP port: %s",
port_id)
def _fix_or_kill_floating_port(self, context, port_id):
pager = base_obj.Pager(limit=1)
fips = l3_obj.FloatingIP.get_objects(
context, _pager=pager, floating_port_id=port_id)
if fips:
LOG.warning("Found incorrect device_id on floating port "
"%(pid)s, correcting to %(fip)s.",
{'pid': port_id, 'fip': fips[0].id})
self._core_plugin.update_port(
context, port_id, {'port': {'device_id': fips[0].id}})
else:
LOG.warning("Found floating IP port %s without floating IP, "
"deleting.", port_id)
self._core_plugin.delete_port(
context, port_id, l3_port_check=False)
def _get_dead_floating_port_candidates(self, context):
filters = {'device_id': ['PENDING'],
'device_owner': [DEVICE_OWNER_FLOATINGIP]}
return {p['id'] for p in self._core_plugin.get_ports(context, filters)}
@db_api.CONTEXT_READER
def _get_router(self, context, router_id):
try:
router = model_query.get_by_id(
context, l3_models.Router, router_id)
except exc.NoResultFound:
raise l3_exc.RouterNotFound(router_id=router_id)
return router
def _make_router_dict(self, router, fields=None, process_extensions=True):
res = dict((key, router[key]) for key in CORE_ROUTER_ATTRS)
if router['gw_port_id']:
ext_gw_info = {
'network_id': router.gw_port['network_id'],
'external_fixed_ips': [{'subnet_id': ip["subnet_id"],
'ip_address': ip["ip_address"]}
for ip in router.gw_port['fixed_ips']]}
else:
ext_gw_info = None
res.update({
EXTERNAL_GW_INFO: ext_gw_info,
'gw_port_id': router['gw_port_id'],
})
# NOTE(salv-orlando): The following assumes this mixin is used in a
# class inheriting from CommonDbMixin, which is true for all existing
# plugins.
if process_extensions:
resource_extend.apply_funcs(l3_apidef.ROUTERS, res, router)
return lib_db_utils.resource_fields(res, fields)
def _create_router_db(self, context, router, tenant_id):
"""Create the DB object."""
router.setdefault('id', uuidutils.generate_uuid())
router['tenant_id'] = tenant_id
registry.publish(resources.ROUTER, events.BEFORE_CREATE, self,
payload=events.DBEventPayload(
context,
resource_id=router['id'],
states=(router,)))
with db_api.CONTEXT_WRITER.using(context):
# pre-generate id so it will be available when
# configuring external gw port
router_db = l3_models.Router(
id=router['id'],
tenant_id=router['tenant_id'],
name=router['name'],
admin_state_up=router['admin_state_up'],
status=constants.ACTIVE,
description=router.get('description'))
context.session.add(router_db)
registry.publish(resources.ROUTER, events.PRECOMMIT_CREATE, self,
payload=events.DBEventPayload(
context,
resource_id=router['id'],
metadata={'router_db': router_db},
states=(router,)))
return router_db
def _update_gw_for_create_router(self, context, gw_info,
request_body, router_id):
if gw_info:
with db_utils.context_if_transaction(
context, not utils.is_session_active(context.session),
writer=False):
router_db = self._get_router(context, router_id)
self._update_router_gw_info(context, router_id,
gw_info, request_body,
router=router_db)
return self._get_router(context, router_id), None
return None, None
def _get_stripped_router(self, router_body):
stripped_router = {}
for key in router_body:
if getattr(l3_models.Router, key, None) or getattr(
l3_attrs_models.RouterExtraAttributes, key, None):
stripped_router[key] = router_body[key]
return stripped_router
@db_api.retry_if_session_inactive()
def create_router(self, context, router):
r = router['router']
gw_info = r.get(EXTERNAL_GW_INFO, None)
create = functools.partial(self._create_router_db, context, r,
r['tenant_id'])
delete = functools.partial(self.delete_router, context)
update_gw = functools.partial(self._update_gw_for_create_router,
context, gw_info, r)
router_db, _unused = db_utils.safe_creation(context, create,
delete, update_gw,
transaction=False)
new_router = self._make_router_dict(router_db)
registry.publish(resources.ROUTER, events.AFTER_CREATE, self,
payload=events.DBEventPayload(
context,
resource_id=router_db.id,
metadata={'request_attrs': r,
'router_db': router_db},
states=(new_router,)))
return new_router
def _update_router_db(self, context, router_id, data):
"""Update the DB object."""
with db_api.CONTEXT_WRITER.using(context):
router_db = self._get_router(context, router_id)
old_router = self._make_router_dict(router_db)
if data:
router_db.update(self._get_stripped_router(data))
registry.publish(resources.ROUTER, events.PRECOMMIT_UPDATE, self,
payload=events.DBEventPayload(
context, request_body=data,
states=(old_router,), resource_id=router_id,
desired_state=router_db))
return router_db
@db_api.retry_if_session_inactive()
def update_router(self, context, id, router):
r = router['router']
gw_info = r.get(EXTERNAL_GW_INFO, constants.ATTR_NOT_SPECIFIED)
original = self.get_router(context, id)
if gw_info != constants.ATTR_NOT_SPECIFIED:
self._update_router_gw_info(context, id, gw_info, r)
router_db = self._update_router_db(context, id, r)
updated = self._make_router_dict(router_db)
registry.publish(resources.ROUTER, events.AFTER_UPDATE, self,
payload=events.DBEventPayload(
context,
resource_id=id,
metadata={'request_attrs': r,
'router_db': router_db},
states=(original, updated)))
return updated
def _create_router_gw_port(self, context, router, network_id, ext_ips):
# Port has no 'tenant-id', as it is hidden from user
port_data = {'tenant_id': '', # intentionally not set
'network_id': network_id,
'fixed_ips': ext_ips or constants.ATTR_NOT_SPECIFIED,
'device_id': router['id'],
'device_owner': DEVICE_OWNER_ROUTER_GW,
'admin_state_up': True,
'name': ''}
if utils.is_session_active(context.session):
# TODO(ralonsoh): ML2 plugin "create_port" should be called outside
# a DB transaction. In this case an exception is made but in order
# to prevent future errors, this call should be moved outside
# the current transaction.
context.GUARD_TRANSACTION = False
gw_port = plugin_utils.create_port(
self._core_plugin, context.elevated(), {'port': port_data})
if not gw_port['fixed_ips']:
LOG.debug('No IPs available for external network %s',
network_id)
with plugin_utils.delete_port_on_error(
self._core_plugin, context.elevated(), gw_port['id']):
with db_api.CONTEXT_WRITER.using(context):
router = self._get_router(context, router['id'])
router.gw_port = self._core_plugin._get_port(
context.elevated(), gw_port['id'])
router_port = l3_obj.RouterPort(
context,
router_id=router.id,
port_id=gw_port['id'],
port_type=DEVICE_OWNER_ROUTER_GW
)
router_port.create()
def _validate_gw_info(self, context, info, ext_ips, router):
network_id = info['network_id'] if info else None
gw_subnets = []
if network_id:
network_db = self._core_plugin._get_network(context, network_id)
if not network_db.external:
msg = _("Network %s is not an external network") % network_id
raise n_exc.BadRequest(resource='router', msg=msg)
gw_subnets = network_db.subnets
for ext_ip in ext_ips:
for subnet in network_db.subnets:
if not subnet.gateway_ip:
continue
if ext_ip.get('ip_address') == subnet.gateway_ip:
msg = _("External IP %s is the same as the "
"gateway IP") % ext_ip.get('ip_address')
raise n_exc.BadRequest(resource='router', msg=msg)
method_validate_routes = getattr(self, '_validate_routes', None)
if not method_validate_routes or not router.route_list:
return network_id
cidrs = []
ip_addresses = []
# All attached ports but the GW port, if exists, that will change
# because the GW information is being updated.
attached_ports = [rp.port for rp in router.attached_ports if
rp.port.id != router.gw_port_id]
for port in attached_ports:
for ip in port.fixed_ips:
cidrs.append(self._core_plugin.get_subnet(
context.elevated(), ip.subnet_id)['cidr'])
ip_addresses.append(ip.ip_address)
# NOTE(ralonsoh): the GW port is not updated yet and the its IP address
# won't be added to "ip_addresses", only the subnet CIDRs.
for gw_subnet in gw_subnets:
cidrs.append(gw_subnet.cidr)
method_validate_routes(context, router.id, router.route_list,
cidrs=cidrs, ip_addresses=ip_addresses)
return network_id
# NOTE(yamamoto): This method is an override point for plugins
# inheriting this class. Do not optimize this out.
def router_gw_port_has_floating_ips(self, context, router_id):
"""Return True if the router's gateway port is serving floating IPs."""
return bool(self.get_floatingips_count(context,
{'router_id': [router_id]}))
def _delete_current_gw_port(self, context, router_id, router,
new_network_id, request_body=None):
"""Delete gw port if attached to an old network."""
port_requires_deletion = (
router.gw_port and router.gw_port['network_id'] != new_network_id)
if not port_requires_deletion:
return
admin_ctx = context.elevated()
old_network_id = router.gw_port['network_id']
if self.router_gw_port_has_floating_ips(admin_ctx, router_id):
raise l3_exc.RouterExternalGatewayInUseByFloatingIp(
router_id=router_id, net_id=router.gw_port['network_id'])
gw_ips = [x['ip_address'] for x in router.gw_port['fixed_ips']]
gw_port_id = router.gw_port['id']
self._delete_router_gw_port_db(context, router, request_body)
if utils.is_session_active(admin_ctx.session):
# TODO(ralonsoh): ML2 plugin "delete_port" should be called outside
# a DB transaction. In this case an exception is made but in order
# to prevent future errors, this call should be moved outside
# the current transaction.
admin_ctx.GUARD_TRANSACTION = False
self._core_plugin.delete_port(
admin_ctx, gw_port_id, l3_port_check=False)
# TODO(boden): normalize metadata
metadata = {'network_id': old_network_id,
'new_network_id': new_network_id,
'gateway_ips': gw_ips}
registry.publish(resources.ROUTER_GATEWAY,
events.AFTER_DELETE, self,
payload=events.DBEventPayload(
context, states=(router,),
metadata=metadata,
resource_id=router_id))
def _delete_router_gw_port_db(self, context, router, request_body):
with db_api.CONTEXT_WRITER.using(context):
router.gw_port = None
if router not in context.session:
context.session.add(router)
try:
registry.publish(resources.ROUTER_GATEWAY,
events.BEFORE_DELETE, self,
payload=events.DBEventPayload(
context, states=(router,),
request_body=request_body,
resource_id=router.id))
except exceptions.CallbackFailure as e:
# NOTE(armax): preserve old check's behavior
if len(e.errors) == 1:
raise e.errors[0].error
raise l3_exc.RouterInUse(router_id=router.id, reason=e)
def _create_gw_port(self, context, router_id, router, new_network_id,
ext_ips):
with db_api.CONTEXT_READER.using(context):
router = self._get_router(context, router_id)
new_valid_gw_port_attachment = (
new_network_id and
(not router.gw_port or
router.gw_port['network_id'] != new_network_id))
if new_valid_gw_port_attachment:
subnets = self._core_plugin.get_subnets_by_network(context,
new_network_id)
try:
registry.publish(
resources.ROUTER_GATEWAY, events.BEFORE_CREATE, self,
payload=events.DBEventPayload(
context,
metadata={
'network_id': new_network_id,
'subnets': subnets},
resource_id=router_id))
except exceptions.CallbackFailure as e:
# raise the underlying exception
raise e.errors[0].error
self._check_for_dup_router_subnets(context, router,
new_network_id,
subnets)
self._create_router_gw_port(context, router,
new_network_id, ext_ips)
with db_api.CONTEXT_READER.using(context):
router = self._get_router(context, router_id)
gw_ips = [x['ip_address'] for x in router.gw_port['fixed_ips']]
registry.publish(resources.ROUTER_GATEWAY,
events.AFTER_CREATE,
self._create_gw_port,
payload=events.DBEventPayload(
context, states=(router,),
metadata={'gateway_ips': gw_ips,
'network_id': new_network_id},
resource_id=router_id))
def _update_current_gw_port(self, context, router_id, router,
ext_ips, request_body):
registry.publish(resources.ROUTER_GATEWAY, events.BEFORE_UPDATE, self,
payload=events.DBEventPayload(
context, request_body=request_body,
states=(router,)))
self._core_plugin.update_port(context.elevated(), router.gw_port['id'],
{'port': {'fixed_ips': ext_ips}})
def _update_router_gw_info(self, context, router_id, info,
request_body, router=None):
router = router or self._get_router(context, router_id)
gw_port = router.gw_port
ext_ips = info.get('external_fixed_ips', []) if info else []
ext_ip_change = self._check_for_external_ip_change(
context, gw_port, ext_ips)
network_id = self._validate_gw_info(context, info, ext_ips, router)
if gw_port and ext_ip_change and gw_port['network_id'] == network_id:
self._update_current_gw_port(context, router_id, router,
ext_ips, request_body)
else:
self._delete_current_gw_port(context, router_id, router,
network_id, request_body)
self._create_gw_port(context, router_id, router, network_id,
ext_ips)
def _check_for_external_ip_change(self, context, gw_port, ext_ips):
# determine if new external IPs differ from the existing fixed_ips
if not ext_ips:
# no external_fixed_ips were included
return False
if not gw_port:
return True
subnet_ids = set(ip['subnet_id'] for ip in gw_port['fixed_ips'])
new_subnet_ids = set(f['subnet_id'] for f in ext_ips
if f.get('subnet_id'))
subnet_change = not new_subnet_ids == subnet_ids
if subnet_change:
return True
ip_addresses = set(ip['ip_address'] for ip in gw_port['fixed_ips'])
new_ip_addresses = set(f['ip_address'] for f in ext_ips
if f.get('ip_address'))
ip_address_change = not ip_addresses == new_ip_addresses
return ip_address_change
def _ensure_router_not_in_use(self, context, router_id):
"""Ensure that no internal network interface is attached
to the router.
"""
router = self._get_router(context, router_id)
device_owner = self._get_device_owner(context, router)
attached_ports = [rp.port_id for rp in router.attached_ports if
rp.port_type == device_owner]
if attached_ports:
reason = 'has ports still attached: ' + ', '.join(attached_ports)
raise l3_exc.RouterInUse(router_id=router_id, reason=reason)
return router
@db_api.retry_if_session_inactive()
def delete_router(self, context, id):
registry.publish(resources.ROUTER, events.BEFORE_DELETE, self,
payload=events.DBEventPayload(
context, resource_id=id))
# TODO(nati) Refactor here when we have router insertion model
with db_api.CONTEXT_READER.using(context):
router = self._ensure_router_not_in_use(context, id)
original = self._make_router_dict(router)
self._delete_current_gw_port(context, id, router, None)
with db_api.CONTEXT_WRITER.using(context):
# TODO(ralonsoh): move this section (port deletion) out of the DB
# transaction.
router_ports_ids = (rp.port_id for rp in
l3_obj.RouterPort.get_objects(context, router_id=id))
if utils.is_session_active(context.session):
context.GUARD_TRANSACTION = False
for rp_id in router_ports_ids:
self._core_plugin.delete_port(context.elevated(), rp_id,
l3_port_check=False)
router = self._get_router(context, id)
registry.publish(resources.ROUTER, events.PRECOMMIT_DELETE, self,
payload=events.DBEventPayload(
context,
resource_id=id,
states=(router,)))
# we bump the revision even though we are about to delete to throw
# staledataerror if something stuck in with a new interface
router.bump_revision()
context.session.flush()
context.session.delete(router)
registry.publish(resources.ROUTER, events.AFTER_DELETE, self,
payload=events.DBEventPayload(
context, resource_id=id,
states=(original,)))
@db_api.retry_if_session_inactive()
def get_router(self, context, id, fields=None):
router = self._get_router(context, id)
return self._make_router_dict(router, fields)
@db_api.retry_if_session_inactive()
@db_api.CONTEXT_READER
def get_routers(self, context, filters=None, fields=None,
sorts=None, limit=None, marker=None,
page_reverse=False):
marker_obj = lib_db_utils.get_marker_obj(
self, context, 'router', limit, marker)
return model_query.get_collection(context, l3_models.Router,
self._make_router_dict,
filters=filters, fields=fields,
sorts=sorts,
limit=limit,
marker_obj=marker_obj,
page_reverse=page_reverse)
@db_api.retry_if_session_inactive()
@db_api.CONTEXT_READER
def get_routers_count(self, context, filters=None):
return model_query.get_collection_count(
context, l3_models.Router, filters=filters,
query_field=l3_models.Router.id.key)
def _check_for_dup_router_subnets(self, context, router,
network_id, new_subnets):
# It's possible these ports are on the same network, but
# different subnets.
new_subnet_ids = {s['id'] for s in new_subnets}
router_subnets = []
for p in (rp.port for rp in router.attached_ports):
for ip in p['fixed_ips']:
if ip['subnet_id'] in new_subnet_ids:
msg = (_("Router already has a port on subnet %s")
% ip['subnet_id'])
raise n_exc.BadRequest(resource='router', msg=msg)
if p.get('device_owner') == DEVICE_OWNER_ROUTER_GW:
ext_subts = self._core_plugin.get_subnets(
context.elevated(),
filters={'network_id': [p['network_id']]})
for sub in ext_subts:
router_subnets.append(sub['id'])
else:
router_subnets.append(ip['subnet_id'])
# Ignore temporary Prefix Delegation CIDRs
new_subnets = [s for s in new_subnets
if s['cidr'] != constants.PROVISIONAL_IPV6_PD_PREFIX]
id_filter = {'id': router_subnets}
subnets = self._core_plugin.get_subnets(context.elevated(),
filters=id_filter)
for sub in subnets:
cidr = sub['cidr']
ipnet = netaddr.IPNetwork(cidr)
for s in new_subnets:
new_cidr = s['cidr']
new_ipnet = netaddr.IPNetwork(new_cidr)
match1 = netaddr.all_matching_cidrs(new_ipnet, [cidr])
match2 = netaddr.all_matching_cidrs(ipnet, [new_cidr])
if match1 or match2:
data = {'subnet_cidr': new_cidr,
'subnet_id': s['id'],
'cidr': cidr,
'sub_id': sub['id']}
msg = (_("Cidr %(subnet_cidr)s of subnet "
"%(subnet_id)s overlaps with cidr %(cidr)s "
"of subnet %(sub_id)s") % data)
raise n_exc.BadRequest(resource='router', msg=msg)
def _get_device_owner(self, context, router=None):
"""Get device_owner for the specified router."""
# NOTE(armando-migliaccio): in the base case this is invariant
return DEVICE_OWNER_ROUTER_INTF
def _validate_interface_info(self, interface_info, for_removal=False):
port_id_specified = interface_info and 'port_id' in interface_info
subnet_id_specified = interface_info and 'subnet_id' in interface_info
if not (port_id_specified or subnet_id_specified):
msg = _("Either subnet_id or port_id must be specified")
raise n_exc.BadRequest(resource='router', msg=msg)
for key in ('port_id', 'subnet_id'):
if key not in interface_info:
continue
err = validators.validate_uuid(interface_info[key])
if err:
raise n_exc.BadRequest(resource='router', msg=err)
if not for_removal:
if port_id_specified and subnet_id_specified:
msg = _("Cannot specify both subnet-id and port-id")
raise n_exc.BadRequest(resource='router', msg=msg)
return port_id_specified, subnet_id_specified
def _check_router_port(self, context, port_id, device_id):
"""Check that a port is available for an attachment to a router
:param context: The context of the request.
:param port_id: The port to be attached.
:param device_id: This method will check that device_id corresponds to
the device_id of the port. It raises PortInUse exception if it
doesn't.
:returns: The port description returned by the core plugin.
:raises: PortInUse if the device_id is not the same as the port's one.
:raises: BadRequest if the port has no fixed IP.
"""
port = self._core_plugin.get_port(context, port_id)
if port['device_id'] != device_id:
raise n_exc.PortInUse(net_id=port['network_id'],
port_id=port['id'],
device_id=port['device_id'])
if not port['fixed_ips']:
msg = _('Router port must have at least one fixed IP')
raise n_exc.BadRequest(resource='router', msg=msg)
fixed_ips = list(port['fixed_ips'])
for fixed_ip in fixed_ips:
subnet = self._core_plugin.get_subnet(
context, fixed_ip['subnet_id'])
self._validate_subnet_address_mode(subnet)
return port
def _validate_port_in_range_or_admin(self, context, subnets, port):
if context.is_admin:
return
subnets_by_id = {}
for s in subnets:
addr_set = netaddr.IPSet()
for range in s['allocation_pools']:
addr_set.add(netaddr.IPRange(netaddr.IPAddress(range['start']),
netaddr.IPAddress(range['end'])))
subnets_by_id[s['id']] = (addr_set, s['project_id'],)
for subnet_id, ip in [(fix_ip['subnet_id'], fix_ip['ip_address'],)
for fix_ip in port['fixed_ips']]:
if (ip not in subnets_by_id[subnet_id][0] and
context.project_id != subnets_by_id[subnet_id][1]):
msg = (_('Cannot add interface to router because specified '
'port %(port)s has an IP address out of the '
'allocation pool of subnet %(subnet)s, which is not '
'owned by the project making the request') %
{'port': port['id'], 'subnet': subnet_id})
raise n_exc.BadRequest(resource='router', msg=msg)
def _validate_router_port_info(self, context, router, port_id):
with db_api.CONTEXT_READER.using(context):
# check again within transaction to mitigate race
port = self._check_router_port(context, port_id, router.id)
# Only allow one router port with IPv6 subnets per network id
if self._port_has_ipv6_address(port):
for existing_port in (rp.port for rp in router.attached_ports):
if (existing_port['network_id'] == port['network_id'] and
self._port_has_ipv6_address(existing_port)):
msg = _("Cannot have multiple router ports with the "
"same network id if both contain IPv6 "
"subnets. Existing port %(p)s has IPv6 "
"subnet(s) and network id %(nid)s")
raise n_exc.BadRequest(resource='router', msg=msg % {
'p': existing_port['id'],
'nid': existing_port['network_id']})
fixed_ips = list(port['fixed_ips'])
subnets = []
for fixed_ip in fixed_ips:
subnet = self._core_plugin.get_subnet(context,
fixed_ip['subnet_id'])
subnets.append(subnet)
if subnets:
self._check_for_dup_router_subnets(context, router,
port['network_id'],
subnets)
# Keep the restriction against multiple IPv4 subnets
if len([s for s in subnets if s['ip_version'] == 4]) > 1:
msg = _("Cannot have multiple "
"IPv4 subnets on router port")
raise n_exc.BadRequest(resource='router', msg=msg)
self._validate_port_in_range_or_admin(context, subnets, port)
return port, subnets
def _notify_attaching_interface(self, context, router_db, port,
interface_info):
"""Notify third party code that an interface is being attached to a
router
:param context: The context of the request.
:param router_db: The router db object having an interface attached.
:param port: The port object being attached to the router.
:param interface_info: The requested interface attachment info passed
to add_router_interface.
:raises: RouterInterfaceAttachmentConflict if a third party code
prevent the port to be attach to the router.
"""
try:
metadata = {
'port': port, 'interface_info': interface_info,
'network_id': port['network_id']}
registry.publish(resources.ROUTER_INTERFACE,
events.BEFORE_CREATE, self,
payload=events.DBEventPayload(
context, states=(router_db,),
metadata=metadata,
resource_id=router_db.id))
except exceptions.CallbackFailure as e:
# raise the underlying exception
reason = (_('cannot perform router interface attachment '
'due to %(reason)s') % {'reason': e})
raise l3_exc.RouterInterfaceAttachmentConflict(reason=reason)
def _add_interface_by_port(self, context, router, port_id, owner):
# Update owner before actual process in order to avoid the
# case where a port might get attached to a router without the
# owner successfully updating due to an unavailable backend.
self._core_plugin.update_port(
context, port_id, {'port': {'device_id': router.id,
'device_owner': owner}})
return self._validate_router_port_info(context, router, port_id)
def _port_has_ipv6_address(self, port):
for fixed_ip in port['fixed_ips']:
if netaddr.IPNetwork(fixed_ip['ip_address']).version == 6:
return True
def _find_ipv6_router_port_by_network(self, context, router, net_id):
router_dev_owner = self._get_device_owner(context, router)
for port in router.attached_ports:
p = port['port']
if p['device_owner'] != router_dev_owner:
# we don't want any special purpose internal ports
continue
if p['network_id'] == net_id and self._port_has_ipv6_address(p):
return port
def _add_interface_by_subnet(self, context, router, subnet_id, owner):
subnet = self._core_plugin.get_subnet(context, subnet_id)
if not subnet['gateway_ip']:
msg = _('Subnet for router interface must have a gateway IP')
raise n_exc.BadRequest(resource='router', msg=msg)
if subnet['project_id'] != context.project_id and not context.is_admin:
msg = (_('Cannot add interface to router because subnet %s is not '
'owned by project making the request') % subnet_id)
raise n_exc.BadRequest(resource='router', msg=msg)
self._validate_subnet_address_mode(subnet)
self._check_for_dup_router_subnets(context, router,
subnet['network_id'], [subnet])
fixed_ip = {'ip_address': subnet['gateway_ip'],
'subnet_id': subnet['id']}
if (subnet['ip_version'] == 6 and not
ipv6_utils.is_ipv6_pd_enabled(subnet)):
# Add new prefix to an existing ipv6 port with the same network id
# if one exists
port = self._find_ipv6_router_port_by_network(context, router,
subnet['network_id'])
if port:
fixed_ips = list(map(dict, port['port']['fixed_ips']))
fixed_ips.append(fixed_ip)
return (self._core_plugin.update_port(
context, port['port_id'],
{'port': {'fixed_ips': fixed_ips}}),
[subnet],
False)
port_data = {'tenant_id': router.tenant_id,
'network_id': subnet['network_id'],
'fixed_ips': [fixed_ip],
'admin_state_up': True,
'device_id': router.id,
'device_owner': owner,
'name': ''}
return plugin_utils.create_port(
self._core_plugin, context, {'port': port_data}), [subnet], True
@staticmethod
def _make_router_interface_info(
router_id, tenant_id, port_id, network_id, subnet_id, subnet_ids):
return {
'id': router_id,
'tenant_id': tenant_id,
'port_id': port_id,
'network_id': network_id,
'subnet_id': subnet_id, # deprecated by IPv6 multi-prefix
'subnet_ids': subnet_ids
}
@db_api.retry_if_session_inactive()
def add_router_interface(self, context, router_id, interface_info=None):
router = self._get_router(context, router_id)
add_by_port, add_by_sub = self._validate_interface_info(interface_info)
device_owner = self._get_device_owner(context, router_id)
# This should be True unless adding an IPv6 prefix to an existing port
new_router_intf = True
cleanup_port = False
if add_by_port:
port_id = interface_info['port_id']
port = self._check_router_port(context, port_id, '')
revert_value = {'device_id': '',
'device_owner': port['device_owner']}
with plugin_utils.update_port_on_error(
self._core_plugin, context, port_id, revert_value):
port, subnets = self._add_interface_by_port(
context, router, port_id, device_owner)
# add_by_subnet is not used here, because the validation logic of
# _validate_interface_info ensures that either of add_by_* is True.
else:
port, subnets, new_router_intf = self._add_interface_by_subnet(
context, router, interface_info['subnet_id'], device_owner)
cleanup_port = new_router_intf # only cleanup port we created
revert_value = {'device_id': '',
'device_owner': port['device_owner']}
if cleanup_port:
mgr = plugin_utils.delete_port_on_error(
self._core_plugin, context, port['id'])
else:
mgr = plugin_utils.update_port_on_error(
self._core_plugin, context, port['id'], revert_value)
if new_router_intf:
with mgr:
self._notify_attaching_interface(context, router_db=router,
port=port,
interface_info=interface_info)
self._add_router_port(
context, port['id'], router.id, device_owner)
gw_ips = []
gw_network_id = None
if router.gw_port:
gw_network_id = router.gw_port.network_id
gw_ips = [x['ip_address'] for x in router.gw_port.fixed_ips]
cidrs = [x['cidr'] for x in subnets]
metadata = {'interface_info': interface_info,
'new_interface': new_router_intf,
'port': port,
'subnets': subnets,
'cidrs': cidrs,
'gateway_ips': gw_ips,
'network_id': gw_network_id}
registry.publish(resources.ROUTER_INTERFACE,
events.AFTER_CREATE, self,
payload=events.DBEventPayload(
context, metadata=metadata,
states=(router,),
resource_id=router_id))
return self._make_router_interface_info(
router.id, port['tenant_id'], port['id'], port['network_id'],
subnets[-1]['id'], [subnet['id'] for subnet in subnets])
@db_api.retry_if_session_inactive()
def _add_router_port(self, context, port_id, router_id, device_owner):
l3_obj.RouterPort(
context,
port_id=port_id,
router_id=router_id,
port_type=device_owner
).create()
# Update owner after actual process again in order to
# make sure the records in routerports table and ports
# table are consistent.
self._core_plugin.update_port(
context, port_id, {'port': {'device_id': router_id,
'device_owner': device_owner}})
def _check_router_interface_not_in_use(self, router_id, subnet):
context = n_ctx.get_admin_context()
subnet_cidr = netaddr.IPNetwork(subnet['cidr'])
fip_objs = l3_obj.FloatingIP.get_objects(context, router_id=router_id)
pf_plugin = directory.get_plugin(plugin_constants.PORTFORWARDING)
subnet_port_ids = [
port.id for port in
port_obj.Port.get_ports_allocated_by_subnet_id(
context, subnet_id=subnet['id'])]