Debian Codegraph @

networking_bagpipe/bagpipe_bgp/vpn/dataplane_drivers.py

raw
1 # Copyright 2014 Orange
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import abc
16
17 from oslo_config import cfg
18 from oslo_log import log as logging
19 from oslo_utils import versionutils
20 import stevedore
21
22 from networking_bagpipe.bagpipe_bgp.common import config
23 from networking_bagpipe.bagpipe_bgp.common import exceptions as exc
24 from networking_bagpipe.bagpipe_bgp.common import log_decorator
25 from networking_bagpipe.bagpipe_bgp.common import looking_glass as lg
26 from networking_bagpipe.bagpipe_bgp.common import run_command
27 from networking_bagpipe.bagpipe_bgp.common import utils
28 from networking_bagpipe.bagpipe_bgp import constants
29 from networking_bagpipe.bagpipe_bgp.engine import exa
30
31
32 LOG = logging.getLogger(__name__)
33
34
35 # NOTE(tmorin): have dataplane_local_address default to
36 # cfg.CONF.BGP.local_address does not work (import order issue)
37 # TODO(tmorin): list possible values for dataplane_driver,
38 # see what neutron-db-manage does
39 dataplane_common_opts = [
40 cfg.Opt("dataplane_local_address",
41 type=config.InterfaceAddress(),
42 help=("IP address to use as next-hop in our route "
43 "advertisements, will be used to send us "
44 "VPN traffic")),
45 cfg.StrOpt("dataplane_driver", default="dummy",
46 help="Dataplane driver.")
47 ]
48
49
50 for vpn_type in constants.VPN_TYPES:
51 cfg.CONF.register_opts(dataplane_common_opts,
52 constants.config_group(vpn_type))
53
54
55 def register_driver_opts(vpn_type, driver_opts):
56 cfg.CONF.register_opts(driver_opts, constants.config_group(vpn_type))
57
58
59 # prefix for setuptools entry points for dataplane drivers
60 DATAPLANE_DRIVER_ENTRY_POINT_PFX = "bagpipe.dataplane"
61
62
63 def instantiate_dataplane_drivers():
64 LOG.debug("Building dataplane drivers...")
65
66 if 'DATAPLANE_DRIVER' in cfg.CONF:
67 LOG.warning("Config file is obsolete, should have a "
68 "DATAPLANE_DRIVER_IPVPN section instead of"
69 " DATAPLANE_DRIVER")
70
71 drivers = {}
72 for vpn_type in constants.VPN_TYPES:
73 dp_config = cfg.CONF.get(constants.config_group(vpn_type))
74
75 driver_name = dp_config.dataplane_driver
76 LOG.debug("Instantiating dataplane driver for %s, with %s",
77 vpn_type, driver_name)
78 try:
79 driver_class = stevedore.driver.DriverManager(
80 namespace='{}.{}'.format(DATAPLANE_DRIVER_ENTRY_POINT_PFX,
81 vpn_type),
82 name=driver_name,
83 ).driver
84
85 drivers[vpn_type] = driver_class()
86 except Exception:
87 LOG.exception("Error while instantiating dataplane driver for "
88 "%s with %s", vpn_type, driver_name)
89 raise
90
91 return drivers
92
93
94 class DataplaneDriver(lg.LookingGlassLocalLogger, utils.ClassReprMixin,
95 metaclass=abc.ABCMeta):
96 '''Dataplane driver
97
98 The initialisation workflow is the following:
99 - on startup, the selected dataplane driver is loaded (its __init__ is
100 called)
101 - on the first attachment of an interface that matches the driver's type
102 the following happens:
103 * the driver reset_state() method is called
104 * the driver initialize() method is called
105
106 The cleanup workflow (what happens when bagpipe-bgp-cleanup is called) is
107 the following:
108 - the dataplane driver is loaded (its __init__ is called)
109 - reset_state() method is called
110
111 As a consequence, whether some init action should go in __init__ or
112 initialize depends on what reset_state does:
113 - __init__ should not do things that reset_state will revert
114 - initialize can do things that reset_state will revert
115 '''
116
117 type = None
118
119 dataplane_instance_class = object # has to be overridden by subclasses
120 encaps = [exa.Encapsulation(exa.Encapsulation.Type.DEFAULT),
121 exa.Encapsulation(exa.Encapsulation.Type.MPLS)]
122 ecmp_support = False
123 required_kernel = None
124
125 driver_opts = []
126
127 @log_decorator.log
128 def __init__(self):
129 lg.LookingGlassLocalLogger.__init__(self)
130
131 cfg.CONF.register_opts(self.driver_opts,
132 constants.config_group(self.type))
133
134 self.config = cfg.CONF.get(constants.config_group(self.type))
135
136 assert issubclass(self.dataplane_instance_class, VPNInstanceDataplane)
137
138 self.local_address = self.config.get("dataplane_local_address")
139
140 if self.local_address is None:
141 self.local_address = cfg.CONF.BGP.local_address
142
143 self.log.info("Will use %s as local_address", self.local_address)
144
145 # Linux kernel version check
146 o = self._run_command("uname -r")
147 self.kernel_release = o[0][0].split("-")[0]
148 if self.required_kernel:
149 kernel_release_version = versionutils.convert_version_to_tuple(
150 self.kernel_release)
151 required_kernel_version = versionutils.convert_version_to_tuple(
152 self.required_kernel)
153 if kernel_release_version < required_kernel_version:
154 self.log.warning("%s requires at least Linux kernel %s"
155 " (you are running %s)",
156 self.__class__.__name__,
157 self.required_kernel,
158 self.kernel_release)
159
160 # Flag to trigger cleanup all dataplane states on first call to
161 # vif_plugged
162 self.first_init = True
163
164 @abc.abstractmethod
165 def reset_state(self):
166 '''dataplane cleanup hook (abstract)
167
168 This method is called:
169 - right before the work on the first attachment begins (initialize()
170 is called afterwards)
171 - by bagpipe-bgp-cleanup
172 '''
173 pass
174
175 def initialize(self):
176 '''dataplane initialization hook
177
178 This is called after reset_state (which, e.g. cleans up the stuff
179 possibly left-out by a previous run).
180
181 Things that are reverted by reset_state() should go here.
182 '''
183 pass
184
185 @log_decorator.log_info
186 def initialize_dataplane_instance(self, instance_id, external_instance_id,
187 gateway_ip, mask,
188 instance_label, **kwargs):
189 '''per-VPN dataplane instanciation
190
191 returns a VPNInstanceDataplane subclass
192 after calling reset_state on the dataplane driver, if this is the first
193 call to initialize_dataplane_instance
194 '''
195
196 if self.first_init:
197 self.log.info("First VPN instance init, reinitializing dataplane"
198 " state")
199 try:
200 self.reset_state()
201 except Exception as e:
202 self.log.error("Exception while resetting state: %s", e)
203
204 try:
205 self.initialize()
206 except Exception as e:
207 self.log.error("Exception while initializing dataplane"
208 " state: %s", e)
209 raise
210
211 self.first_init = False
212 else:
213 self.log.debug("(not reinitializing dataplane state)")
214
215 return self.dataplane_instance_class(self, instance_id,
216 external_instance_id,
217 gateway_ip, mask,
218 instance_label, **kwargs)
219
220 def get_local_address(self):
221 return self.local_address
222
223 def supported_encaps(self):
224 return self.__class__.encaps
225
226 def needs_cleanup_assist(self):
227 '''Control per-route cleanup events
228
229 A dataplane driver not able to cleanup all the states for a given
230 VPN instance can return True here to receive artifical dataplane
231 removal calls, such as remove_dataplane_for_remote_endpoint, for
232 each state previously setup
233 '''
234 return False
235
236 def validate_directions(self, direction):
237 # by default, assume a driver only supports plugging in both directions
238 # if a driver does not support forwarding only the traffic to the port,
239 # (and hence omit forwarding traffic from the port), it should raise an
240 # exception if directions is TO_PORT
241 # if a driver does not support forwarding only the traffic from the
242 # port (and hence omit forwarding traffic to the port), it should raise
243 # an exception if directions is FROM_PORT
244 if (direction is not None) and (direction != constants.BOTH):
245 self.log.warning("Unsupported direction: %s", direction)
246 raise exc.APIException("Unsupported direction: %s" % direction)
247
248 def _run_command(self, command, run_as_root=False, *args, **kwargs):
249 return run_command.run_command(self.log, command, run_as_root,
250 *args, **kwargs)
251
252 def get_lg_map(self):
253 encaps = []
254 for encap in self.supported_encaps():
255 encaps.append(repr(encap))
256 return {
257 "name": (lg.VALUE, self.__class__.__name__),
258 "local_address": (lg.VALUE, self.local_address),
259 "supported_encaps": (lg.VALUE, encaps),
260 "config": (lg.VALUE, utils.osloconfig_json_serialize(self.config)),
261 "kernel_release": (lg.VALUE, self.kernel_release)
262 }
263
264
265 class VPNInstanceDataplane(lg.LookingGlassLocalLogger, metaclass=abc.ABCMeta):
266
267 @log_decorator.log_info
268 def __init__(self, dataplane_driver, instance_id, external_instance_id,
269 gateway_ip, network_plen, instance_label=None, **kwargs):
270 lg.LookingGlassLocalLogger.__init__(self, repr(instance_id))
271 self.driver = dataplane_driver
272 self.config = dataplane_driver.config
273 self.instance_id = instance_id
274 self.external_instance_id = external_instance_id
275 self.gateway_ip = gateway_ip
276 self.network_plen = network_plen
277 self.instance_label = instance_label
278
279 @abc.abstractmethod
280 def cleanup(self):
281 pass
282
283 @abc.abstractmethod
284 def vif_plugged(self, mac_address, ip_address_prefix, localport, label,
285 direction):
286 pass
287
288 @abc.abstractmethod
289 def vif_unplugged(self, mac_address, ip_address_prefix, localport, label,
290 direction, last_endpoint=True):
291 pass
292
293 def update_fallback(self, fallback):
294 if fallback is not None:
295 self.log.warning("fallback specified (%s) but not supported by "
296 "driver, ignoring", fallback)
297
298 @abc.abstractmethod
299 def setup_dataplane_for_remote_endpoint(self, prefix, remote_pe, label,
300 nlri, encaps,
301 lb_consistent_hash_order=0):
302 pass
303
304 @abc.abstractmethod
305 def remove_dataplane_for_remote_endpoint(self, prefix, remote_pe, label,
306 nlri, encaps,
307 lb_consistent_hash_order=0):
308 pass
309
310 def needs_cleanup_assist(self):
311 '''Control per-route cleanup events
312
313 A dataplane driver not able to cleanup all the states for a given
314 VPN instance can return True here to receive artifical dataplane
315 removal calls, such as remove_dataplane_for_remote_endpoint, for
316 each state previously setup
317 '''
318 return self.driver.needs_cleanup_assist()
319
320 def _run_command(self, command, run_as_root=False, *args, **kwargs):
321 return run_command.run_command(self.log, command, run_as_root,
322 *args, **kwargs)
323
324 def __repr__(self):
325 return "%s<%d>" % (self.__class__.__name__, self.instance_id)
326
327 # Looking glass info ####
328
329 def get_lg_local_info(self, path_prefix):
330 driver = {"id": self.driver.type,
331 "href": lg.get_absolute_path(
332 "DATAPLANE_DRIVERS", path_prefix, [self.driver.type])}
333 return {
334 "driver": driver,
335 }
336
337
338 class DummyVPNInstanceDataplane(VPNInstanceDataplane):
339
340 @log_decorator.log
341 def __init__(self, *args, **kwargs):
342 VPNInstanceDataplane.__init__(self, *args)
343
344 @log_decorator.log
345 def vif_plugged(self, *args, **kwargs):
346 pass
347
348 @log_decorator.log
349 def vif_unplugged(self, *args, **kwargs):
350 pass
351
352 @log_decorator.log
353 def update_fallback(self, *args, **kwargs):
354 pass
355
356 @log_decorator.log
357 def setup_dataplane_for_remote_endpoint(self, *args, **kwargs):
358 pass
359
360 @log_decorator.log
361 def remove_dataplane_for_remote_endpoint(self, *args, **kwargs):
362 pass
363
364 @log_decorator.log
365 def cleanup(self, *args, **kwargs):
366 pass
367
368
369 class DummyDataplaneDriver(DataplaneDriver):
370
371 dataplane_instance_class = DummyVPNInstanceDataplane
372
373 def __init__(self, *args):
374 DataplaneDriver.__init__(self, *args)
375 self.log.warning("Dummy dataplane driver, won't do anything useful")
376
377 @log_decorator.log_info
378 def initialize(self, *args, **kwargs):
379 pass
380
381 @log_decorator.log_info
382 def reset_state(self, *args, **kwargs):
383 pass