Repository navigation
Expand file tree
/
Copy pathundersync_mech.py
More file actions
273 lines (228 loc) · 10.4 KB
/
Copy pathundersync_mech.py
File metadata and controls
273 lines (228 loc) · 10.4 KB
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
import logging
from neutron_lib import constants as p_const
from neutron_lib import exceptions as exc
from neutron_lib.api.definitions import portbindings
from neutron_lib.callbacks import events
from neutron_lib.callbacks import priority_group
from neutron_lib.callbacks import registry
from neutron_lib.callbacks import resources
from neutron_lib.plugins.ml2 import api
from neutron_lib.plugins.ml2.api import MechanismDriver
from oslo_config import cfg
from neutron_understack import config
from neutron_understack import lag_name
from neutron_understack import utils
from neutron_understack.undersync_client import Undersync
from .ml2_type_annotations import PortContext
LOG = logging.getLogger(__name__)
SUPPORTED_VNIC_TYPES = [portbindings.VNIC_BAREMETAL]
# Run after the understack trunk driver's handler for the same event, so its
# segment deallocation has finished before we tell Undersync to reconcile.
# neutron-lib sorts subscribers ascending and understack uses PRIORITY_DEFAULT.
# A distinct priority is also required because neutron-lib stores `cancellable`
# per priority *group*: mechanism drivers initialize before the trunk plugin, so
# sharing the default group would let our flag decide the trunk driver's.
TRUNK_EVENT_PRIORITY = priority_group.PRIORITY_DEFAULT + 1000
class MechanismDriverOrderError(exc.NeutronException):
message = (
"The undersync mechanism driver must be listed after understack in "
"[ml2] mechanism_drivers, but the configured order is %(drivers)s."
)
def _missing_physnet_msg(port_id: str) -> str:
"""physical_network names the VLAN group Undersync configures."""
return (
"physical_network is required in the binding_profile for baremetal port "
f"trunk configuration, but port {port_id} does not have one."
)
class UndersyncDriver(MechanismDriver):
"""Tells Undersync which vlan groups need their switch config reconciled.
Sole owner of the Undersync client. Allocates nothing and mutates no trunk
state: it observes what the understack driver did and names the affected
physical_network to Undersync.
Must be listed *after* ``understack`` in ml2 ``mechanism_drivers``: ML2
invokes ``*_postcommit`` in that order, so understack has finished releasing
segments and cleaning trunks before we sync. ``initialize()`` refuses to
start otherwise.
"""
@property
def connectivity(self): # type: ignore
return portbindings.CONNECTIVITY_L2
def initialize(self):
self._check_driver_order()
config.register_ml2_understack_opts(cfg.CONF)
self.undersync = Undersync(cfg.CONF.ml2_understack.undersync_url)
self.subscribe()
@staticmethod
def _check_driver_order() -> None:
"""Fail at startup rather than drift silently at runtime.
Listed first, this driver would tell Undersync to reconcile before
understack has released the port's segment, so the old VLAN would stay
on the switch until the next sync of that vlan group.
"""
drivers = list(cfg.CONF.ml2.mechanism_drivers)
if "understack" not in drivers or "undersync" not in drivers:
return
if drivers.index("undersync") < drivers.index("understack"):
raise MechanismDriverOrderError(drivers=",".join(drivers))
def subscribe(self):
# Reject a teardown we could not notify Undersync about while the
# transaction can still be aborted; AFTER_DELETE is too late to raise.
# PRIORITY_DEFAULT is fine here: a failed precommit callback always
# raises, whatever the group's cancellable flag says.
for resource in (resources.SUBPORTS, resources.TRUNK):
registry.subscribe(
self._validate_parent_physnet,
resource,
events.PRECOMMIT_DELETE,
cancellable=True,
)
for callback, resource, event in (
(self._subports_after_create, resources.SUBPORTS, events.AFTER_CREATE),
(self._subports_after_delete, resources.SUBPORTS, events.AFTER_DELETE),
(self._trunk_after_delete, resources.TRUNK, events.AFTER_DELETE),
):
registry.subscribe(
callback,
resource,
event,
priority=TRUNK_EVENT_PRIORITY,
cancellable=True,
)
def update_port_precommit(self, context: PortContext) -> None:
"""Store the LAG name of a bonded port in its binding profile.
Only generated when not already present. Runs inside the port update's
transaction, so an anchor we cannot name aborts the update.
update_port_postcommit and delete_port_postcommit then read
``local_group_information["lag"]`` back from the profile.
"""
if not utils.is_baremetal_port(context):
return
profile = context.current.get(portbindings.PROFILE) or {}
group = profile.get("local_group_information")
if not group:
return
if group.get("lag"):
return
try:
group["lag"] = lag_name.for_profile(profile)
except lag_name.InvalidLagAnchor:
LOG.exception("Cannot name the LAG for port %s", context.current["id"])
raise
utils.set_active_binding_profile(
context.plugin_context, context.current["id"], profile
)
def update_port_postcommit(self, context: PortContext) -> None:
if not utils.is_baremetal_port(context):
return
# Only context.original still carries a binding profile once unbound.
if utils.is_port_unbinding(context):
port = context.original
elif utils.is_port_bound_to_switchport(context):
port = context.current
else:
return
physnet = port[portbindings.PROFILE].get("physical_network")
if physnet:
LOG.debug(
"syncing vlan group %s, lag %s", physnet, self._postcommit_lag(port)
)
self.undersync.sync(physnet)
def _postcommit_lag(self, port: dict) -> str | None:
"""Best-effort LAG name; bind_port already rejected unnameable anchors."""
try:
return self._lag_for(port)
except lag_name.InvalidLagAnchor:
LOG.error("Cannot name the LAG for port %s", port["id"])
return None
def delete_port_postcommit(self, context: PortContext) -> None:
# Releasing the segment stays with the understack driver; we only
# reconcile the switch for the vlan group the port named.
if not utils.is_baremetal_port(context):
return
port = context.current
physnet = port[portbindings.PROFILE].get("physical_network")
if physnet:
LOG.debug(
"syncing vlan group %s, lag %s", physnet, self._postcommit_lag(port)
)
self.undersync.sync(physnet)
def _validate_parent_physnet(self, resource, event, trunk_plugin, payload):
trunk = payload.states[0]
# A trunk with no subports has no switchport config to tear down, so it
# is allowed through even without a physnet.
if resource == resources.TRUNK and not trunk.sub_ports:
return
parent_port = utils.fetch_port_object(trunk.port_id)
if not utils.parent_port_is_bound(parent_port):
return
if not utils.active_port_binding(parent_port).profile.get(api.PHYSICAL_NETWORK):
raise exc.BadRequest(
resource="port", msg=_missing_physnet_msg(parent_port.id)
)
def _subports_after_create(self, resource, event, trunk_plugin, payload):
self._sync_trunk_parent(payload.states[0])
def _subports_after_delete(self, resource, event, trunk_plugin, payload):
self._sync_trunk_parent(payload.states[0])
def _trunk_after_delete(self, resource, event, trunk_plugin, payload):
trunk = payload.states[0]
if trunk.sub_ports:
self._sync_trunk_parent(trunk)
def _sync_trunk_parent(self, trunk) -> None:
parent_port = utils.fetch_port_object(trunk.port_id)
if not utils.parent_port_is_bound(parent_port):
return
physnet = utils.active_port_binding(parent_port).profile.get(
api.PHYSICAL_NETWORK
)
if not physnet:
# _validate_parent_physnet rejects this while it is still
# abortable, so the binding profile changed underneath us. Raising
# postcommit from a cancellable subscription surfaces as a 500.
LOG.error(_missing_physnet_msg(parent_port.id))
return
LOG.debug("notifying Undersync of vlan group %s", physnet)
self.undersync.sync(physnet)
@staticmethod
def _lag_for(port: dict) -> str | None:
"""The port-channel name for a bonded port, or None if not bonded.
Raises InvalidLagAnchor if the anchor cannot be named.
"""
return lag_name.for_profile(port.get(portbindings.PROFILE) or {})
def bind_port(self, context: PortContext) -> None:
port = context.current
vnic_type = port.get(portbindings.VNIC_TYPE, portbindings.VNIC_NORMAL)
LOG.debug(
"bind_port called for port %s vnic_type %s segments %s",
port["id"],
vnic_type,
context.segments_to_bind,
)
if vnic_type not in SUPPORTED_VNIC_TYPES:
LOG.debug("Skipping unsupported vnic_type %s", vnic_type)
return
binding_profile = port.get(portbindings.PROFILE) or {}
if not binding_profile.get("physical_network"):
LOG.debug(
"Skipping port %s without a physical_network in its binding_profile",
port["id"],
)
return
for segment in context.segments_to_bind:
if segment[api.NETWORK_TYPE] == p_const.TYPE_VLAN:
LOG.debug(
"bind_port: setting binding for port %s on VLAN segment %s",
port["id"],
segment,
)
context.set_binding(
segment_id=segment[api.ID],
vif_type=portbindings.VIF_TYPE_OTHER,
vif_details={},
status=p_const.PORT_STATUS_ACTIVE,
)
return
LOG.warning(
"bind_port: no VLAN segment found for port %s in %s",
port["id"],
context.segments_to_bind,
)