Debian Codegraph @

networking_bagpipe/bagpipe_bgp/engine/exabgp_peer_worker.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 collections
16 import logging as python_logging
17 import select
18 import time
19
20 from exabgp.bgp import fsm as exa_fsm
21 from exabgp.bgp import message as exa_message
22 from exabgp.bgp.message import open as exa_open
23 from exabgp.bgp import neighbor as exa_neighbor
24 from exabgp.environment import getenv
25 from exabgp.environment import parsing as exa_parsing
26 from exabgp.logger import option as exa_log_option
27 from exabgp.protocol import family as exa_family
28 from exabgp import reactor as exa_reactor
29 from exabgp.reactor import peer as exa_peer
30 from oslo_config import cfg
31 from oslo_log import log as logging
32
33 from networking_bagpipe._i18n import _
34 from networking_bagpipe.bagpipe_bgp.common import looking_glass as lg
35 from networking_bagpipe.bagpipe_bgp import engine
36 from networking_bagpipe.bagpipe_bgp.engine import bgp_peer_worker
37 from networking_bagpipe.bagpipe_bgp.engine import exa
38
39
40 LOG = logging.getLogger(__name__)
41
42
43 def setup_exabgp_env():
44 # initialize/tweak ExaBGP config and log internals
45
46 env = getenv()
47 # tell exabgp to parse routes:
48 env.log.routes = True
49
50 # Note(lajoskatona): exabgp 5.0.0, changed how logging is handled, relying
51 # on standard python logging, so just need to ensure it uses oslo_log
52 # finally
53 # Set up exabgp to use oslo_log logger
54 exa_log_option.logger = logging.getLogger(__name__ + ".exabgp")
55 exa_log_option.formater = lambda msg, src, lvl, ts=None: (
56 msg if exa_log_option.short else "%-13s %s" % (src, msg)
57 )
58
59 env.log.enable = True
60
61 if LOG.logger.getEffectiveLevel():
62 env.log.level = exa_parsing.syslog_value(
63 python_logging.getLevelName(LOG.logger.getEffectiveLevel())
64 )
65 else:
66 env.log.level = exa_parsing.syslog_value('INFO')
67 env.log.all = True
68 env.log.packets = True
69
70 # monkey patch exabgp to work around exabgp issue #690
71 # only relevant for exabgp 4.0.2
72 # ( https://github.com/Exa-Networks/exabgp/issues/690 )
73 if hasattr(exa_family.Family, 'size'):
74 exa_family.Family.size[(exa_family.AFI.l2vpn,
75 exa_family.SAFI.evpn)] = ((4,), 0)
76
77
78 TRANSLATE_EXABGP_STATE = {exa_fsm.FSM.IDLE: bgp_peer_worker.FSM.Idle,
79 exa_fsm.FSM.ACTIVE: bgp_peer_worker.FSM.Active,
80 exa_fsm.FSM.CONNECT: bgp_peer_worker.FSM.Connect,
81 exa_fsm.FSM.OPENSENT: bgp_peer_worker.FSM.OpenSent,
82 exa_fsm.FSM.OPENCONFIRM:
83 bgp_peer_worker.FSM.OpenConfirm,
84 exa_fsm.FSM.ESTABLISHED:
85 bgp_peer_worker.FSM.Established,
86 }
87
88
89 class ExaBGPPeerWorker(bgp_peer_worker.BGPPeerWorker, lg.LookingGlassMixin):
90
91 enabled_families = [(exa.AFI.ipv4, exa.SAFI.mpls_vpn),
92 # (exa.exa.AFI.ipv6, exa.SAFI.mpls_vpn),
93 (exa.AFI.l2vpn, exa.SAFI.evpn),
94 (exa.AFI.ipv4, exa.SAFI.flow_vpn)]
95
96 def __init__(self, bgp_manager, peer_address):
97 bgp_peer_worker.BGPPeerWorker.__init__(self, bgp_manager, peer_address)
98
99 self.local_address = cfg.CONF.BGP.local_address
100 self.peer_address = peer_address
101
102 self.peer = None
103
104 self.rtc_active = False
105 self._active_families = []
106
107 # hooks into BGPPeerWorker state changes
108
109 def _stop_and_clean(self):
110 super()._stop_and_clean()
111
112 self._active_families = []
113
114 if self.peer is not None:
115 self.log.info("Clearing peer")
116 if self.peer.proto:
117 self.peer.proto.close()
118 self.peer.stop()
119 self.peer = None
120
121 def _to_established(self):
122 super()._to_established()
123
124 if self.rtc_active:
125 self.log.debug("RTC active, subscribing to all RTC routes")
126 # subscribe to RTC routes, to be able to propagate them from
127 # internal workers to this peer
128 self._subscribe(exa.AFI.ipv4, exa.SAFI.rtc)
129 else:
130 self.log.debug("RTC inactive, subscribing to all active families")
131 # if we don't use RTC with our peer, then we need to see events for
132 # all routes of all active families, to be able to send them to him
133 for (afi, safi) in self._active_families:
134 self._subscribe(afi, safi)
135
136 # implementation of BGPPeerWorker abstract methods
137
138 def _initiate_connection(self):
139 self.log.debug("Initiate ExaBGP connection to %s:%s from %s",
140 self.peer_address, cfg.CONF.BGP.bgp_port,
141 self.local_address)
142
143 self.rtc_active = False
144
145 neighbor = exa_neighbor.Neighbor()
146 neighbor.make_rib()
147 neighbor.router_id = exa_open.RouterID(self.local_address)
148 neighbor.local_as = exa.ASN(cfg.CONF.BGP.my_as)
149 # no support for eBGP yet:
150 neighbor.peer_as = exa.ASN(cfg.CONF.BGP.my_as)
151 neighbor.local_address = exa.IP.create(self.local_address)
152 neighbor.md5_ip = exa.IP.create(self.local_address)
153 neighbor.peer_address = exa.IP.create(self.peer_address)
154 neighbor.hold_time = exa_open.HoldTime(
155 bgp_peer_worker.DEFAULT_HOLDTIME)
156 neighbor.connect = cfg.CONF.BGP.bgp_port
157 neighbor.api = collections.defaultdict(list)
158 neighbor.extended_message = False
159
160 for afi_safi in self.enabled_families:
161 neighbor.add_family(afi_safi)
162
163 if cfg.CONF.BGP.enable_rtc:
164 # how to test fot this ?
165 neighbor.add_family((exa.AFI.ipv4, exa.SAFI.rtc))
166
167 self.log.debug("Instantiate ExaBGP Peer")
168 self.peer = exa_peer.Peer(neighbor, None)
169
170 try:
171 for action in self.peer._establish():
172 self.fsm.state = TRANSLATE_EXABGP_STATE[
173 self.peer.fsm.state]
174
175 if action == exa_peer.ACTION.LATER:
176 time.sleep(2)
177 elif action == exa_peer.ACTION.NOW:
178 time.sleep(0.1)
179
180 if self.should_stop:
181 self.log.debug("We're closing, raise StoppedException")
182 raise bgp_peer_worker.StoppedException()
183
184 if action == exa_peer.ACTION.CLOSE:
185 self.log.debug("Socket status is CLOSE, "
186 "raise InitiateConnectionException")
187 raise bgp_peer_worker.InitiateConnectionException(
188 "Socket is closed")
189 except exa_peer.Interrupted:
190 self.log.debug("Connect was interrupted, "
191 "raise InitiateConnectionException")
192 raise bgp_peer_worker.InitiateConnectionException(
193 "Connect was interrupted")
194 except exa_message.Notify as e:
195 self.log.debug("Notify: %s", e)
196 if (e.code, e.subcode) == (1, 1):
197 raise bgp_peer_worker.OpenWaitTimeout(str(e))
198 else:
199 raise Exception(_("Notify received: %s" % e))
200 except exa_reactor.network.error.LostConnection:
201 raise
202
203 # check the capabilities of the session just established...
204
205 self.protocol = self.peer.proto
206
207 received_open = self.protocol.negotiated.received_open
208
209 self._set_hold_time(self.protocol.negotiated.holdtime)
210
211 mp_capabilities = received_open.capabilities.get(
212 exa_open.capability.Capability.CODE.MULTIPROTOCOL, [])
213
214 # check that our peer advertized at least mpls_vpn and evpn
215 # capabilities
216 self._active_families = []
217 for (afi, safi) in (self.__class__.enabled_families +
218 [(exa.AFI.ipv4, exa.SAFI.rtc)]):
219 if (afi, safi) not in mp_capabilities:
220 if (((afi, safi) != (exa.AFI.ipv4, exa.SAFI.rtc)) or
221 cfg.CONF.BGP.enable_rtc):
222 self.log.warning("Peer does not advertise (%s,%s) "
223 "capability", afi, safi)
224 else:
225 self.log.info(
226 "Family (%s,%s) successfully negotiated with peer %s",
227 afi, safi, self.peer_address)
228 self._active_families.append((afi, safi))
229
230 if len(self._active_families) == 0:
231 self.log.error("No family was negotiated for VPN routes")
232
233 self.rtc_active = False
234
235 if cfg.CONF.BGP.enable_rtc:
236 if (exa.AFI.ipv4, exa.SAFI.rtc) in mp_capabilities:
237 self.log.info(
238 "RTC successfully enabled with peer %s", self.peer_address)
239 self.rtc_active = True
240 else:
241 self.log.warning(
242 "enable_rtc True but peer not configured for RTC")
243
244 def _receive_loop_fun(self):
245
246 try:
247 select.select([self.protocol.connection.io], [], [], 2)
248
249 if not self.protocol.connection:
250 raise Exception(_("lost connection"))
251
252 message = next(self.protocol.read_message())
253
254 if message.ID != exa_message.NOP.ID:
255 self.log.debug("protocol read message: %s", message)
256 except exa_message.Notification as e:
257 self.log.error("Notification: %s", e)
258 return 2
259 except exa_reactor.network.error.LostConnection as e:
260 self.log.warning("Lost connection while waiting for message: %s",
261 e)
262 return 2
263 except TypeError as e:
264 self.log.error("Error while reading BGP message: %s", e)
265 return 2
266 except Exception as e:
267 self.log.error("Error while reading BGP message: %s", e)
268 raise
269
270 if message.ID == exa_message.NOP.ID:
271 return 1
272 if message.ID == exa_message.Update.ID:
273 if self.fsm.state != bgp_peer_worker.FSM.Established:
274 raise Exception(
275 _("Update received but not in Established state"))
276 # more below
277 elif message.ID == exa_message.KeepAlive.ID:
278 self.enqueue(bgp_peer_worker.KEEP_ALIVE_RECEIVED)
279 self.log.debug("Received message: %s", message)
280 else:
281 self.log.warning("Received unexpected message: %s", message)
282
283 if isinstance(message, exa_message.Update):
284 if message.nlris:
285 for nlri in message.nlris:
286 if nlri.action == exa_message.IN.ANNOUNCED:
287 action = engine.RouteEvent.ADVERTISE
288 elif nlri.action == exa_message.IN.WITHDRAWN:
289 action = engine.RouteEvent.WITHDRAW
290 else:
291 raise Exception(_("should not be reached (action:%s)" %
292 nlri.action))
293 self._process_received_route(action, nlri,
294 message.attributes)
295 return 1
296
297 def _process_received_route(self, action, nlri, attributes):
298 self.log.info("Received route: %s, %s", nlri, attributes)
299
300 route_entry = engine.RouteEntry(nlri, None, attributes)
301
302 if action == exa_message.IN.ANNOUNCED:
303 self._advertise_route(route_entry)
304 elif action == exa_message.IN.WITHDRAWN:
305 self._withdraw_route(route_entry)
306 else:
307 raise Exception(_("unsupported action ??? (%s)" % action))
308
309 # TODO(tmmorin): move RTC code out-of the peer-specific code
310 if (nlri.afi, nlri.safi) == (exa.AFI.ipv4, exa.SAFI.rtc):
311 self.log.info("Received an RTC route")
312
313 if nlri.rt is None:
314 self.log.info("Received RTC is a wildcard")
315
316 # the semantic of RTC routes does not distinguish between AFI/SAFIs
317 # if our peer subscribed to a Route Target, it means that we needs
318 # to send him all routes of any AFI/SAFI carrying this RouteTarget.
319 for (afi, safi) in self._active_families:
320 if (afi, safi) != (exa.AFI.ipv4, exa.SAFI.rtc):
321 if action == exa_message.IN.ANNOUNCED:
322 self._subscribe(afi, safi, nlri.rt)
323 elif action == exa_message.IN.WITHDRAWN:
324 self._unsubscribe(afi, safi, nlri.rt)
325 else:
326 raise Exception(_("unsupported action ??? (%s)"
327 % action))
328
329 def _send(self, data):
330 # (error if state not the right one for sending updates)
331 self.log.debug("Sending %d bytes on socket to peer %s",
332 len(data), self.peer_address)
333 try:
334 for _unused in self.protocol.connection.writer(data):
335 pass
336 except Exception:
337 self.log.exception("Was not able to send data")
338
339 def _keep_alive_message_data(self):
340 return exa_message.KeepAlive().message()
341
342 def _update_for_route_event(self, event):
343 try:
344 r = exa_message.Update([event.route_entry.nlri],
345 event.route_entry.attributes)
346 return b''.join(r.messages(self.protocol.negotiated))
347 except Exception:
348 self.log.exception("Exception while generating message for "
349 "route %s", r)
350 return b''
351
352 # Looking Glass ###############
353
354 def get_lg_local_info(self, path_prefix):
355 return {
356 "peeringAddresses": {"peer_address": self.peer_address,
357 "local_address": self.local_address},
358 "as_info": {"local": cfg.CONF.BGP.my_as,
359 "peer": cfg.CONF.BGP.my_as},
360 "rtc": {"active": self.rtc_active,
361 "enabled": cfg.CONF.BGP.enable_rtc},
362 "active_families": [repr(f) for f in self._active_families],
363 }