/
ovn_client.py
2833 lines (2505 loc) · 129 KB
/
ovn_client.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 2019 Red Hat, 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 collections
import copy
import datetime
import netaddr
from neutron_lib.api.definitions import l3
from neutron_lib.api.definitions import l3_ext_gw_multihoming
from neutron_lib.api.definitions import port_security as psec
from neutron_lib.api.definitions import portbindings
from neutron_lib.api.definitions import provider_net as pnet
from neutron_lib.api.definitions import segment as segment_def
from neutron_lib import constants as const
from neutron_lib import context as n_context
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 p_utils
from neutron_lib.services.logapi import constants as log_const
from neutron_lib.services.qos import constants as qos_consts
from neutron_lib.utils import helpers
from neutron_lib.utils import net as n_net
from oslo_config import cfg
from oslo_log import log
from oslo_utils import excutils
from oslo_utils import strutils
from oslo_utils import timeutils
from oslo_utils import versionutils
from ovsdbapp.backend.ovs_idl import idlutils
import tenacity
from neutron._i18n import _
from neutron.common.ovn import acl as ovn_acl
from neutron.common.ovn import constants as ovn_const
from neutron.common.ovn import utils
from neutron.common import utils as common_utils
from neutron.conf.agent import ovs_conf
from neutron.conf.plugins.ml2.drivers.ovn import ovn_conf
from neutron.db import ovn_revision_numbers_db as db_rev
from neutron.db import segments_db
from neutron.objects import router
from neutron.plugins.ml2 import db as ml2_db
from neutron.plugins.ml2.drivers.ovn.mech_driver.ovsdb.extensions \
import placement as placement_extension
from neutron.plugins.ml2.drivers.ovn.mech_driver.ovsdb.extensions \
import qos as qos_extension
LOG = log.getLogger(__name__)
OvnPortInfo = collections.namedtuple(
"OvnPortInfo",
[
"type",
"options",
"addresses",
"port_security",
"parent_name",
"tag",
"dhcpv4_options",
"dhcpv6_options",
"cidrs",
"device_owner",
"security_group_ids",
"address4_scope_id",
"address6_scope_id",
"vnic_type",
"capabilities",
"mtu",
],
)
GW_INFO = collections.namedtuple('GatewayInfo', ['network_id', 'subnet_id',
'router_ip', 'gateway_ip',
'ip_version', 'ip_prefix'])
class OVNClient(object):
def __init__(self, nb_idl, sb_idl):
self._nb_idl = nb_idl
self._sb_idl = sb_idl
self._plugin_property = None
self._l3_plugin_property = None
self._is_mcast_flood_broken = None
self._is_ipxe_over_ipv6_supported = None
# TODO(ralonsoh): handle the OVN client extensions with an ext. manager
self._qos_driver = qos_extension.OVNClientQosExtension(driver=self)
self.placement_extension = (
placement_extension.OVNClientPlacementExtension(self))
@property
def _plugin(self):
if self._plugin_property is None:
self._plugin_property = directory.get_plugin()
return self._plugin_property
@property
def _l3_plugin(self):
if self._l3_plugin_property is None:
self._l3_plugin_property = directory.get_plugin(
plugin_constants.L3)
return self._l3_plugin_property
def _transaction(self, commands, txn=None):
"""Create a new transaction or add the commands to an existing one."""
if txn is None:
with self._nb_idl.transaction(check_error=True) as new_txn:
for cmd in commands:
new_txn.add(cmd)
else:
for cmd in commands:
txn.add(cmd)
def is_external_ports_supported(self):
return self._nb_idl.is_col_present(
'Logical_Switch_Port', 'ha_chassis_group')
# TODO(ihrachys) remove when min OVN version >= 21.06
def is_allow_stateless_supported(self):
return self._nb_idl.is_col_supports_value('ACL', 'action',
'allow-stateless')
def _get_allowed_addresses_from_port(self, port):
if not port.get(psec.PORTSECURITY):
return [], []
if utils.is_lsp_trusted(port):
return [], []
allowed_addresses = set()
new_macs = set()
addresses = port['mac_address']
for ip in port.get('fixed_ips', []):
addresses += ' ' + ip['ip_address']
for allowed_address in port.get('allowed_address_pairs', []):
# If allowed address pair has same mac as the port mac,
# append the allowed ip address to the 'addresses'.
# Else we will have multiple entries for the same mac in
# 'Logical_Switch_Port.port_security'.
if allowed_address['mac_address'] == port['mac_address']:
addresses += ' ' + allowed_address['ip_address']
else:
allowed_addresses.add(allowed_address['mac_address'] + ' ' +
allowed_address['ip_address'])
new_macs.add(allowed_address['mac_address'])
allowed_addresses.add(addresses)
return list(allowed_addresses), list(new_macs)
def _get_subnet_dhcp_options_for_port(self, port, ip_version):
"""Returns the subnet dhcp options for the port.
Return the first found DHCP options belong for the port.
"""
subnets = [
fixed_ip['subnet_id']
for fixed_ip in port['fixed_ips']
if netaddr.IPAddress(fixed_ip['ip_address']).version == ip_version]
get_opts = self._nb_idl.get_subnets_dhcp_options(subnets)
if get_opts:
if ip_version == const.IP_VERSION_6:
# Always try to find a dhcpv6 stateful v6 subnet to return.
# This ensures port can get one stateful v6 address when port
# has multiple dhcpv6 stateful and stateless subnets.
for opts in get_opts:
# We are setting ovn_const.DHCPV6_STATELESS_OPT to "true"
# in _get_ovn_dhcpv6_opts, so entries in DHCP_Options table
# should have unicode type 'true' if they were defined as
# dhcpv6 stateless.
if opts['options'].get(
ovn_const.DHCPV6_STATELESS_OPT) != 'true':
return opts
return get_opts[0]
def _get_port_dhcp_options(self, port, ip_version):
"""Return dhcp options for port.
In case the port is dhcp disabled, or IP addresses it has belong
to dhcp disabled subnets, returns None.
Otherwise, returns a dict:
- with content from a existing DHCP_Options row for subnet, if the
port has no extra dhcp options.
- with only one item ('cmd', AddDHCPOptionsCommand(..)), if the port
has extra dhcp options. The command should be processed in the same
transaction with port creating or updating command to avoid orphan
row issue happen.
"""
lsp_dhcp_disabled, lsp_dhcp_opts = utils.get_lsp_dhcp_opts(
port, ip_version)
if lsp_dhcp_disabled:
return
subnet_dhcp_options = self._get_subnet_dhcp_options_for_port(
port, ip_version)
if not subnet_dhcp_options:
# NOTE(lizk): It's possible for Neutron to configure a port with IP
# address belongs to subnet disabled dhcp. And no DHCP_Options row
# will be inserted for such a subnet. So in that case, the subnet
# dhcp options here will be None.
return
if not lsp_dhcp_opts:
return subnet_dhcp_options
# This port has extra DHCP options defined, so we will create a new
# row in DHCP_Options table for it.
subnet_dhcp_options['options'].update(lsp_dhcp_opts)
subnet_dhcp_options['external_ids'].update(
{'port_id': port['id']})
subnet_id = subnet_dhcp_options['external_ids']['subnet_id']
add_dhcp_opts_cmd = self._nb_idl.add_dhcp_options(
subnet_id, port_id=port['id'],
cidr=subnet_dhcp_options['cidr'],
options=subnet_dhcp_options['options'],
external_ids=subnet_dhcp_options['external_ids'])
return {'cmd': add_dhcp_opts_cmd}
@tenacity.retry(retry=tenacity.retry_if_exception_type(RuntimeError),
wait=tenacity.wait_random(min=2, max=3),
stop=tenacity.stop_after_attempt(3),
reraise=True)
def _wait_for_port_bindings_host(self, context, port_id):
db_port = ml2_db.get_port(context, port_id)
# This is already checked previously but, just to stay on
# the safe side in case the port is deleted mid-operation
if not db_port:
raise RuntimeError(
_('No port found with ID %s') % port_id)
if not db_port.port_bindings:
raise RuntimeError(
_('No port bindings information found for '
'port %s') % port_id)
if not db_port.port_bindings[0].host:
raise RuntimeError(
_('No hosting information found for port %s') % port_id)
return db_port
def update_lsp_host_info(self, context, db_port, up=True):
"""Update the binding hosting information for the LSP.
Update the binding hosting information in the Logical_Switch_Port
external_ids column. See LP #2020058 for more information.
:param context: Neutron API context.
:param db_port: The Neutron port.
:param up: If True add the host information, if False remove it.
Defaults to True.
"""
cmd = []
if up:
if not db_port.port_bindings:
return
if not db_port.port_bindings[0].host:
# NOTE(lucasgomes): There might be a sync issue between
# the moment that this port was fetched from the database
# and the hosting information being set, retry a few times
try:
db_port = self._wait_for_port_bindings_host(
context, db_port.id)
except RuntimeError as e:
LOG.warning(e)
return
host = db_port.port_bindings[0].host
ext_ids = ('external_ids',
{ovn_const.OVN_HOST_ID_EXT_ID_KEY: host})
cmd.append(
self._nb_idl.db_set(
'Logical_Switch_Port', db_port.id, ext_ids))
else:
cmd.append(
self._nb_idl.db_remove(
'Logical_Switch_Port', db_port.id, 'external_ids',
ovn_const.OVN_HOST_ID_EXT_ID_KEY, if_exists=True))
self._transaction(cmd)
# TODO(lucasagomes): Remove this method and the logic around the broken
# mcast_flood_reports configuration option on any other port that is not
# type "localnet" when the fixed version of OVN becomes the norm.
# The commit in core OVN fixing this issue is the
# https://github.com/ovn-org/ovn/commit/6aeeccdf272bc60630581e46aa42d97f4f56d4fa
@property
def is_mcast_flood_broken(self):
if self._is_mcast_flood_broken is None:
schema_version = self._nb_idl.get_schema_version()
self._is_mcast_flood_broken = (
versionutils.convert_version_to_tuple(schema_version) <
(6, 3, 0))
return self._is_mcast_flood_broken
# TODO(slaweq): Remove this method when min supported OVN version will be
# >= v23.06.0 which is the one which have support for IPv6 iPXE booting
# added:
# https://github.com/ovn-org/ovn/commit/c5fd51bd154147a567097eaf61fbebc0b5b39e28
@property
def is_ipxe_over_ipv6_supported(self):
if self._is_ipxe_over_ipv6_supported is None:
schema_version = self._nb_idl.get_schema_version()
self._is_ipxe_over_ipv6_supported = (
versionutils.convert_version_to_tuple(schema_version) >=
(7, 0, 4))
return self._is_ipxe_over_ipv6_supported
def _get_port_options(self, port):
context = n_context.get_admin_context()
bp_info = utils.validate_and_get_data_from_binding_profile(port)
vtep_physical_switch = bp_info.bp_param.get('vtep-physical-switch')
port_type = ''
cidrs = ''
address4_scope_id = ""
address6_scope_id = ""
dhcpv4_options = self._get_port_dhcp_options(port, const.IP_VERSION_4)
dhcpv6_options = self._get_port_dhcp_options(port, const.IP_VERSION_6)
mtu = ''
if vtep_physical_switch:
vtep_logical_switch = bp_info.bp_param.get('vtep-logical-switch')
port_type = 'vtep'
options = {'vtep-physical-switch': vtep_physical_switch,
'vtep-logical-switch': vtep_logical_switch}
addresses = [ovn_const.UNKNOWN_ADDR]
parent_name = []
tag = []
port_security = []
else:
options = {}
parent_name = bp_info.bp_param.get('parent_name', [])
tag = bp_info.bp_param.get('tag', [])
address = port['mac_address']
port_fixed_ips = port.get('fixed_ips', [])
subnet_ids = [
ip['subnet_id']
for ip in port_fixed_ips
if 'subnet_id' in ip
]
subnets = self._plugin.get_subnets(
context, filters={'id': subnet_ids})
subnets_by_id = {subnet['id']: subnet for subnet in subnets}
address4_scope_id, address6_scope_id = (
utils.get_subnets_address_scopes(context, subnets_by_id,
port_fixed_ips,
self._plugin))
p_type, virtual_ip, virtual_parents = (
utils.get_port_type_virtual_and_parents(
subnets_by_id, port_fixed_ips, port['network_id'],
port['id'], self._nb_idl))
if p_type:
port_type = ovn_const.LSP_TYPE_VIRTUAL
options[ovn_const.LSP_OPTIONS_VIRTUAL_IP_KEY] = virtual_ip
options[ovn_const.LSP_OPTIONS_VIRTUAL_PARENTS_KEY] = (
virtual_parents)
if subnets_by_id:
for ip in port_fixed_ips:
ip_addr = ip['ip_address']
address += ' ' + ip_addr
subnet = subnets_by_id.get(ip['subnet_id'])
if not subnet:
LOG.debug('Subnet not found for ip address %s',
ip_addr)
continue
cidrs += ' {}/{}'.format(ip['ip_address'],
subnet['cidr'].split('/')[1])
# Metadata or OVN LB HM port.
if (utils.is_ovn_metadata_port(port) or
utils.is_ovn_lb_hm_port(port)):
port_type = ovn_const.LSP_TYPE_LOCALPORT
if utils.is_port_external(port):
if self.is_external_ports_supported():
port_type = ovn_const.LSP_TYPE_EXTERNAL
else:
LOG.warning('The version of OVN used does not support '
'the "external ports" feature used for '
'SR-IOV ports with OVN native DHCP')
addresses = []
port_security, new_macs = (
self._get_allowed_addresses_from_port(port))
# TODO(egarciar): OVN supports MAC learning from v21.03. This
# if-else block is stated so as to keep compatibility with older
# OVN versions and should be removed in the future.
if self._sb_idl.is_table_present('FDB'):
if (port_security or port_type or dhcpv4_options or
dhcpv6_options):
addresses.append(address)
addresses.extend(new_macs)
else:
addresses = [address]
addresses.extend(new_macs)
if not port_security and not port_type:
# Port security is disabled for this port.
# So this port can send traffic with any mac address.
# OVN allows any mac address from a port if "unknown"
# is added to the Logical_Switch_Port.addresses column.
# So add it.
addresses.append(ovn_const.UNKNOWN_ADDR)
# HA Chassis Group will bind the port to the highest
# priority Chassis
if port_type != ovn_const.LSP_TYPE_EXTERNAL:
if (bp_info.vnic_type == portbindings.VNIC_REMOTE_MANAGED and
ovn_const.VIF_DETAILS_PF_MAC_ADDRESS in bp_info.bp_param):
port_net = self._plugin.get_network(
context, port['network_id'])
mtu = str(port_net['mtu'])
options.update({
ovn_const.LSP_OPTIONS_VIF_PLUG_TYPE_KEY: 'representor',
ovn_const.LSP_OPTIONS_VIF_PLUG_MTU_REQUEST_KEY: mtu,
ovn_const.LSP_OPTIONS_VIF_PLUG_REPRESENTOR_PF_MAC_KEY: (
bp_info.bp_param.get(
ovn_const.VIF_DETAILS_PF_MAC_ADDRESS)),
ovn_const.LSP_OPTIONS_VIF_PLUG_REPRESENTOR_VF_NUM_KEY: str(
bp_info.bp_param.get(ovn_const.VIF_DETAILS_VF_NUM))})
chassis = utils.determine_bind_host(self._sb_idl, port)
if chassis:
# If OVN supports multi-chassis port bindings, use it for live
# migration to asynchronously configure destination port while
# VM is migrating
if utils.is_additional_chassis_supported(self._sb_idl):
mdst = port.get(
portbindings.PROFILE, {}).get(
ovn_const.MIGRATING_ATTR)
if mdst:
# Let OVN know that the port should be configured on
# destination too
chassis += ',%s' % mdst
# Block traffic on destination host until libvirt sends
# a RARP packet from it to inform network about the new
# location of the port
options['activation-strategy'] = 'rarp'
# Virtual ports can not be bound by using the requested-chassis
# mechanism, ovn-controller will create the Port_Binding entry
# when it sees an ARP coming from the VIP
if port_type != ovn_const.LSP_TYPE_VIRTUAL:
options[ovn_const.LSP_OPTIONS_REQUESTED_CHASSIS_KEY] = \
chassis
if self.is_mcast_flood_broken and port_type not in (
'vtep', ovn_const.LSP_TYPE_LOCALPORT, 'router'):
options.update({ovn_const.LSP_OPTIONS_MCAST_FLOOD_REPORTS: 'true'})
device_owner = port.get('device_owner', '')
sg_ids = ' '.join(utils.get_lsp_security_groups(port))
return OvnPortInfo(port_type, options, addresses, port_security,
parent_name, tag, dhcpv4_options, dhcpv6_options,
cidrs.strip(), device_owner, sg_ids,
address4_scope_id, address6_scope_id,
bp_info.vnic_type, bp_info.capabilities, mtu
)
def update_port_dhcp_options(self, port_info, txn):
dhcpv4_options = []
dhcpv6_options = []
if not port_info.dhcpv4_options:
dhcpv4_options = []
elif 'cmd' in port_info.dhcpv4_options:
dhcpv4_options = txn.add(port_info.dhcpv4_options['cmd'])
else:
dhcpv4_options = [port_info.dhcpv4_options['uuid']]
if not port_info.dhcpv6_options:
dhcpv6_options = []
elif 'cmd' in port_info.dhcpv6_options:
dhcpv6_options = txn.add(port_info.dhcpv6_options['cmd'])
else:
dhcpv6_options = [port_info.dhcpv6_options['uuid']]
return (dhcpv4_options, dhcpv6_options)
def get_external_ids_from_port(self, port):
port_info = self._get_port_options(port)
external_ids = {
ovn_const.OVN_PORT_NAME_EXT_ID_KEY: port['name'],
ovn_const.OVN_DEVID_EXT_ID_KEY: port['device_id'],
ovn_const.OVN_PROJID_EXT_ID_KEY: port['project_id'],
ovn_const.OVN_CIDRS_EXT_ID_KEY: port_info.cidrs,
ovn_const.OVN_DEVICE_OWNER_EXT_ID_KEY: port_info.device_owner,
ovn_const.OVN_SUBNET_POOL_EXT_ADDR_SCOPE4_KEY:
port_info.address4_scope_id,
ovn_const.OVN_SUBNET_POOL_EXT_ADDR_SCOPE6_KEY:
port_info.address6_scope_id,
ovn_const.OVN_NETWORK_NAME_EXT_ID_KEY:
utils.ovn_name(port['network_id']),
ovn_const.OVN_SG_IDS_EXT_ID_KEY: port_info.security_group_ids,
ovn_const.OVN_REV_NUM_EXT_ID_KEY: str(utils.get_revision_number(
port, ovn_const.TYPE_PORTS)),
ovn_const.OVN_PORT_VNIC_TYPE_KEY: port_info.vnic_type,
ovn_const.OVN_PORT_BP_CAPABILITIES_KEY:
';'.join(port_info.capabilities),
ovn_const.OVN_NETWORK_MTU_EXT_ID_KEY: port_info.mtu,
}
return port_info, external_ids
def create_port(self, context, port):
if utils.is_lsp_ignored(port):
return
port_info, external_ids = self.get_external_ids_from_port(port)
lswitch_name = utils.ovn_name(port['network_id'])
# It's possible to have a network created on one controller and then a
# port created on a different controller quickly enough that the second
# controller does not yet see that network in its local cache of the
# OVN northbound database. Check if the logical switch is present
# or not in the idl's local copy of the database before creating
# the lswitch port.
self._nb_idl.check_for_row_by_value_and_retry(
'Logical_Switch', 'name', lswitch_name)
with self._nb_idl.transaction(check_error=True) as txn:
dhcpv4_options, dhcpv6_options = self.update_port_dhcp_options(
port_info, txn=txn)
# The lport_name *must* be neutron port['id']. It must match the
# iface-id set in the Interfaces table of the Open_vSwitch
# database which nova sets to be the port ID.
kwargs = {
'lport_name': port['id'],
'lswitch_name': lswitch_name,
'addresses': port_info.addresses,
'external_ids': external_ids,
'parent_name': port_info.parent_name,
'tag': port_info.tag,
'enabled': port.get('admin_state_up'),
'options': port_info.options,
'type': port_info.type,
'port_security': port_info.port_security,
'dhcpv4_options': dhcpv4_options,
'dhcpv6_options': dhcpv6_options
}
if (self.is_external_ports_supported() and
port_info.type == ovn_const.LSP_TYPE_EXTERNAL):
kwargs['ha_chassis_group'], _ = (
utils.sync_ha_chassis_group_network(
context, self._nb_idl, self._sb_idl, port['id'],
port['network_id'], txn))
# NOTE(mjozefcz): Do not set addresses if the port is not
# bound, has no device_owner and it is OVN LB VIP port.
# For more details check related bug #1789686.
if (port.get('name').startswith(ovn_const.LB_VIP_PORT_PREFIX) and
not port.get('device_owner') and
port.get(portbindings.VIF_TYPE) ==
portbindings.VIF_TYPE_UNBOUND):
kwargs['addresses'] = []
# Check if the parent port was created with the
# allowed_address_pairs already set
allowed_address_pairs = port.get('allowed_address_pairs', [])
if (allowed_address_pairs and
port_info.type != ovn_const.LSP_TYPE_VIRTUAL):
addrs = [addr['ip_address'] for addr in allowed_address_pairs]
self._set_unset_virtual_port_type(context, txn, port, addrs)
port_cmd = txn.add(self._nb_idl.create_lswitch_port(
**kwargs))
sg_ids = utils.get_lsp_security_groups(port)
# If this is not a trusted port and port security is enabled,
# add it to the default drop Port Group so that all traffic
# is dropped by default.
if not utils.is_lsp_trusted(port) and port_info.port_security:
self._add_port_to_drop_port_group(port_cmd, txn)
# Just add the port to its Port Group.
for sg in sg_ids:
txn.add(self._nb_idl.pg_add_ports(
utils.ovn_port_group_name(sg), port_cmd))
if self.is_dns_required_for_port(port):
self.add_txns_to_sync_port_dns_records(txn, port)
self._qos_driver.create_port(txn, port, port_cmd)
db_rev.bump_revision(context, port, ovn_const.TYPE_PORTS)
def _set_unset_virtual_port_type(self, context, txn, parent_port,
addresses, unset=False):
cmd = self._nb_idl.set_lswitch_port_to_virtual_type
if unset:
cmd = self._nb_idl.unset_lswitch_port_to_virtual_type
for addr in addresses:
virt_port = self._plugin.get_ports(context, filters={
portbindings.VIF_TYPE: portbindings.VIF_TYPE_UNBOUND,
'network_id': [parent_port['network_id']],
'fixed_ips': {'ip_address': [addr]}})
if not virt_port:
continue
virt_port = virt_port[0]
args = {'lport_name': virt_port['id'],
'virtual_parent': parent_port['id'],
'if_exists': True}
LOG.debug("Parent port %(virtual_parent)s found for "
"virtual port %(lport_name)s", args)
if not unset:
args['vip'] = addr
txn.add(cmd(**args))
# TODO(lucasagomes): The ``port_object`` parameter was added to
# keep things backward compatible. Remove it in the Rocky release.
def update_port(self, context, port, port_object=None):
if utils.is_lsp_ignored(port):
return
port_info, external_ids = self.get_external_ids_from_port(port)
check_rev_cmd = self._nb_idl.check_revision_number(
port['id'], port, ovn_const.TYPE_PORTS)
with self._nb_idl.transaction(check_error=True,
revision_mismatch_raise=True) as txn:
txn.add(check_rev_cmd)
columns_dict = {}
if utils.is_lsp_router_port(port):
# It is needed to specify the port type, if not specified
# the AddLSwitchPortCommand will trigger a change
# on the northd status column from UP to DOWN, triggering a
# LogicalSwitchPortUpdateDownEvent, that will most likely
# cause a revision conflict.
# https://bugs.launchpad.net/neutron/+bug/1955578
router_obj = router.Router.get_object(context,
id=port['device_id'])
if utils.is_ovn_provider_router(router_obj):
columns_dict['type'] = ovn_const.LSP_TYPE_ROUTER
port_info.options.update(
self._nb_idl.get_router_port_options(port['id']))
else:
columns_dict['type'] = port_info.type
columns_dict['addresses'] = port_info.addresses
dhcpv4_options, dhcpv6_options = self.update_port_dhcp_options(
port_info, txn=txn)
if utils.is_ovn_metadata_port(port):
context = n_context.get_admin_context()
network = self._plugin.get_network(context, port['network_id'])
subnet_ids = [
_ip['subnet_id']
for _ip in port['fixed_ips']
if 'subnet_id' in _ip
]
for subnet in self._plugin.get_subnets(
context, filters={'id': subnet_ids}):
if not subnet['enable_dhcp']:
continue
self._update_subnet_dhcp_options(subnet, network, txn)
# NOTE(mjozefcz): Do not set addresses if the port is not
# bound, has no device_owner and it is OVN LB VIP port.
# For more details check related bug #1789686.
if (port.get('name').startswith(ovn_const.LB_VIP_PORT_PREFIX) and
not port.get('device_owner') and
port.get(portbindings.VIF_TYPE) ==
portbindings.VIF_TYPE_UNBOUND):
columns_dict['addresses'] = []
if self.is_external_ports_supported():
if port_info.type == ovn_const.LSP_TYPE_EXTERNAL:
columns_dict['ha_chassis_group'], _ = (
utils.sync_ha_chassis_group_network(
context, self._nb_idl, self._sb_idl, port['id'],
port['network_id'], txn))
else:
# Clear the ha_chassis_group field
columns_dict['ha_chassis_group'] = []
ovn_port = self._nb_idl.lookup('Logical_Switch_Port', port['id'])
addr_pairs_diff = utils.compute_address_pairs_diff(ovn_port, port)
if port_info.type != ovn_const.LSP_TYPE_VIRTUAL:
self._set_unset_virtual_port_type(
context, txn, port, addr_pairs_diff.added)
self._set_unset_virtual_port_type(
context, txn, port, addr_pairs_diff.removed,
unset=True)
# Keep key value pairs that were in the original external ids
# of the ovn port and we did not touch.
for k, v in ovn_port.external_ids.items():
external_ids.setdefault(k, v)
# NOTE(lizk): Fail port updating if port doesn't exist. This
# prevents any new inserted resources to be orphan, such as port
# dhcp options or ACL rules for port, e.g. a port was created
# without extra dhcp options and security group, while updating
# includes the new attributes setting to port.
txn.add(self._nb_idl.set_lswitch_port(
lport_name=port['id'],
external_ids=external_ids,
parent_name=port_info.parent_name,
tag=port_info.tag,
options=port_info.options,
enabled=port['admin_state_up'],
port_security=port_info.port_security,
dhcpv4_options=dhcpv4_options,
dhcpv6_options=dhcpv6_options,
if_exists=False,
**columns_dict))
# Determine if security groups or fixed IPs are updated.
old_sg_ids = set(utils.get_ovn_port_security_groups(ovn_port))
new_sg_ids = set(utils.get_lsp_security_groups(port))
detached_sg_ids = old_sg_ids - new_sg_ids
attached_sg_ids = new_sg_ids - old_sg_ids
for sg in detached_sg_ids:
txn.add(self._nb_idl.pg_del_ports(
utils.ovn_port_group_name(sg), port['id']))
for sg in attached_sg_ids:
txn.add(self._nb_idl.pg_add_ports(
utils.ovn_port_group_name(sg), port['id']))
if (not utils.is_lsp_trusted(port) and
utils.is_port_security_enabled(port)):
self._add_port_to_drop_port_group(port['id'], txn)
# If the port doesn't belong to any security group and
# port_security is disabled, or it's a trusted port, then
# allow all traffic.
elif ((not new_sg_ids and
not utils.is_port_security_enabled(port)) or
utils.is_lsp_trusted(port)):
self._del_port_from_drop_port_group(port['id'], txn)
self._qos_driver.update_port(txn, port, port_object)
if self.is_dns_required_for_port(port):
self.add_txns_to_sync_port_dns_records(
txn, port, original_port=port_object)
elif port_object and self.is_dns_required_for_port(port_object):
# We need to remove the old entries
self.add_txns_to_remove_port_dns_records(txn, port_object)
if check_rev_cmd.result == ovn_const.TXN_COMMITTED:
db_rev.bump_revision(context, port, ovn_const.TYPE_PORTS)
def _delete_port(self, port_id, port_object=None):
ovn_port = self._nb_idl.lookup('Logical_Switch_Port', port_id)
ovn_network_name = ovn_port.external_ids.get(
ovn_const.OVN_NETWORK_NAME_EXT_ID_KEY)
network_id = ovn_network_name.replace('neutron-', '')
with self._nb_idl.transaction(check_error=True) as txn:
txn.add(self._nb_idl.delete_lswitch_port(
port_id, ovn_network_name))
p_object = ({'id': port_id, 'network_id': network_id}
if not port_object else port_object)
self._qos_driver.delete_port(txn, p_object)
if port_object and self.is_dns_required_for_port(port_object):
self.add_txns_to_remove_port_dns_records(txn, port_object)
# Check if the port being deleted is a virtual parent
if ovn_port.type != ovn_const.LSP_TYPE_VIRTUAL:
ls = self._nb_idl.ls_get(ovn_network_name).execute(
check_error=True)
cmd = self._nb_idl.unset_lswitch_port_to_virtual_type
for lsp in ls.ports:
if lsp.type != ovn_const.LSP_TYPE_VIRTUAL:
continue
if port_id in lsp.options.get(
ovn_const.LSP_OPTIONS_VIRTUAL_PARENTS_KEY, ''):
txn.add(cmd(lsp.name, port_id, if_exists=True))
# NOTE(lucasagomes): We need to delete the LSP before we attempt
# to remove the HA Chassis Group or it will fail with a violation
# error due to the LSP reference in the group
with self._nb_idl.transaction(check_error=True) as txn:
if ovn_port.type == ovn_const.LSP_TYPE_EXTERNAL:
ha_ch_grp_name = utils.ovn_extport_chassis_group_name(port_id)
txn.add(self._nb_idl.ha_chassis_group_del(
ha_ch_grp_name, if_exists=True))
# TODO(lucasagomes): The ``port_object`` parameter was added to
# keep things backward compatible. Remove it in the Rocky release.
def delete_port(self, context, port_id, port_object=None):
try:
self._delete_port(port_id, port_object=port_object)
except idlutils.RowNotFound:
# NOTE(dalvarez): At this point the port doesn't exist in the OVN
# database or, most likely, this worker IDL hasn't been updated
# yet. See Bug #1960006 for more information. The approach here is
# to allow at least one maintenance cycle before we delete the
# revision number so that the port doesn't stale and eventually
# gets deleted by the maintenance task.
rev_row = db_rev.get_revision_row(context, port_id)
time_ = (timeutils.utcnow() - datetime.timedelta(
seconds=ovn_const.DB_CONSISTENCY_CHECK_INTERVAL + 30))
if rev_row and rev_row.created_at >= time_:
return
except Exception as e:
with excutils.save_and_reraise_exception():
LOG.error('Failed to delete port %(port)s. Error: '
'%(error)s', {'port': port_id, 'error': e})
db_rev.delete_revision(context, port_id, ovn_const.TYPE_PORTS)
def _create_or_update_floatingip(self, floatingip, txn=None):
router_id = floatingip.get('router_id')
if not router_id:
return
# FIPs used for port forwarding have no fixed address
# configured. Also, OVN handler for port forwarding
# is delegated to OVNPortForwarding. Nothing further
# to do here.
if floatingip['fixed_ip_address'] is None:
LOG.debug("Skipping NAT for floating ip %(id)s, external ip "
"%(fip_ip)s on router %(rtr_id)s: no logical_ip",
{'id': floatingip['id'],
'fip_ip': floatingip['floating_ip_address'],
'rtr_id': router_id})
return
commands = []
admin_context = n_context.get_admin_context()
fip_db = self._l3_plugin._get_floatingip(
admin_context, floatingip['id'])
port_db = self._plugin.get_port(
admin_context, fip_db['floating_port_id'])
gw_lrouter_name = utils.ovn_name(router_id)
ext_ids = {
ovn_const.OVN_FIP_EXT_ID_KEY: floatingip['id'],
ovn_const.OVN_REV_NUM_EXT_ID_KEY: str(utils.get_revision_number(
floatingip, ovn_const.TYPE_FLOATINGIPS)),
ovn_const.OVN_FIP_PORT_EXT_ID_KEY: floatingip['port_id'],
ovn_const.OVN_ROUTER_NAME_EXT_ID_KEY: gw_lrouter_name,
ovn_const.OVN_FIP_EXT_MAC_KEY: port_db['mac_address'],
ovn_const.OVN_FIP_NET_ID: floatingip['floating_network_id']}
columns = {'type': 'dnat_and_snat',
'logical_ip': floatingip['fixed_ip_address'],
'external_ip': floatingip['floating_ip_address'],
'logical_port': floatingip['port_id'],
'external_ids': ext_ids}
# If OVN supports gateway_port column for NAT rules set gateway port
# uuid to any floating IP without gw port reference - LP#2035281.
if utils.is_nat_gateway_port_supported(self._nb_idl):
router_db = self._l3_plugin.get_router(admin_context, router_id)
gw_port_id = router_db.get('gw_port_id')
lrp = self._nb_idl.get_lrouter_port(gw_port_id)
columns['gateway_port'] = lrp.uuid
if ovn_conf.is_ovn_distributed_floating_ip():
if self._nb_idl.lsp_get_up(floatingip['port_id']).execute():
columns['external_mac'] = port_db['mac_address']
# TODO(mjozefcz): Remove this workaround when OVN LB
# will support both decentralized FIPs on LB and member.
lb_member_fip = self._is_lb_member_fip(admin_context, floatingip)
if (ovn_conf.is_ovn_distributed_floating_ip() and
lb_member_fip):
LOG.warning("Port %s is configured as a member "
"of one of OVN Load_Balancers and "
"Load_Balancer has FIP assigned. "
"In order to make traffic work member "
"FIP needs to be centralized, even if "
"this environment is configured as DVR. "
"Removing logical_port and external_mac from "
"NAT entry.", floatingip['port_id'])
columns.pop('logical_port', None)
columns.pop('external_mac', None)
commands.append(self._nb_idl.add_nat_rule_in_lrouter(gw_lrouter_name,
**columns))
# Get the logical port (of the private network) and set the field
# external_ids:fip=<FIP>. This will be used by the ovn octavia driver
# to add the floating ip as vip in the Load_Balancer.vips column.
private_lsp = self._nb_idl.get_lswitch_port(floatingip['port_id'])
if private_lsp:
port_fip = {
ovn_const.OVN_PORT_FIP_EXT_ID_KEY:
floatingip['floating_ip_address']}
commands.append(
self._nb_idl.db_set('Logical_Switch_Port', private_lsp.uuid,
('external_ids', port_fip))
)
if not lb_member_fip:
commands.extend(
self._handle_lb_fip_cmds(
admin_context, private_lsp,
action=ovn_const.FIP_ACTION_ASSOCIATE))
else:
LOG.warning("LSP for floatingip %s, has not been found! "
"Cannot set FIP on VIP.",
floatingip['id'])
self._transaction(commands, txn=txn)
def _is_lb_member_fip(self, context, fip):
port = self._plugin.get_port(
context, fip['port_id'])
member_subnet = [ip['subnet_id'] for ip in port['fixed_ips']
if ip['ip_address'] == fip['fixed_ip_address']]
if not member_subnet:
return False
member_subnet = member_subnet[0]
ls = self._nb_idl.lookup(
'Logical_Switch', utils.ovn_name(port['network_id']))
for lb in ls.load_balancer:
for ext_id in lb.external_ids.keys():
if ext_id.startswith(ovn_const.LB_EXT_IDS_POOL_PREFIX):
members = lb.external_ids[ext_id]
if not members:
continue
for member in members.split(','):
if ('%s:' % fip['fixed_ip_address'] in member and
'_%s' % member_subnet in member):
return True
return False
def _handle_lb_fip_cmds(self, context, lb_lsp,
action=ovn_const.FIP_ACTION_ASSOCIATE):
commands = []
if not ovn_conf.is_ovn_distributed_floating_ip():
return commands
lb_lsp_fip_port = lb_lsp.external_ids.get(
ovn_const.OVN_PORT_NAME_EXT_ID_KEY, '')
if not lb_lsp_fip_port.startswith(ovn_const.LB_VIP_PORT_PREFIX):
return commands
# This is a FIP on LB VIP.
# Loop over members and delete FIP external_mac/logical_port enteries.
# Find all LBs with this LSP as VIP.
lbs = self._nb_idl.db_find_rows(
'Load_Balancer',
('external_ids', '=', {
ovn_const.LB_EXT_IDS_VIP_PORT_ID_KEY: lb_lsp.name})
).execute(check_error=True)
for lb in lbs:
# GET all LS where given LB is linked.
ls_linked = [
item
for item in self._nb_idl.db_find_rows(
'Logical_Switch').execute(check_error=True)
if lb in item.load_balancer]
if not ls_linked:
return
# Find out IP addresses and subnets of configured members.
members_to_verify = []
for ext_id in lb.external_ids.keys():
if ext_id.startswith(ovn_const.LB_EXT_IDS_POOL_PREFIX):
members = lb.external_ids[ext_id]
if not members:
continue
for member in members.split(','):
# NOTE(mjozefcz): Remove this workaround in W release.
# Last argument of member info is a subnet_id from
# from which member comes from.
# member_`id`_`ip`:`port`_`subnet_ip`
member_info = member.split('_')
if len(member_info) >= 4:
m = {}
m['id'] = member_info[1]
m['ip'] = member_info[2].split(':')[0]
m['subnet_id'] = member_info[3]
try:
subnet = self._plugin.get_subnet(
context, m['subnet_id'])
m['network_id'] = subnet['network_id']
members_to_verify.append(m)
except n_exc.SubnetNotFound: