Debian Codegraph @

networking_bagpipe/bagpipe_bgp/engine/__init__.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 """This module classes related to producing and consuming events related to
16 BGP routes.
17
18 routes: RouteEntry
19
20 events: RouteEvent
21 an announcement or a withdrawal of a BGP route
22
23 workers: Worker
24 * produce events
25 * subscribe to the route table manager to consume events related to
26 certain BGP routes
27
28 route table manager (singleton)
29 * tracks subscriptions of workers
30 * dispatches events based on subscriptions
31
32 """
33
34 from oslo_log import log as logging
35
36 from networking_bagpipe.bagpipe_bgp.common import log_decorator
37 from networking_bagpipe.bagpipe_bgp.common import looking_glass as lg
38 from networking_bagpipe.bagpipe_bgp.engine import exa
39
40
41 LOG = logging.getLogger(__name__)
42
43
44 class RouteEntry(lg.LookingGlassMixin):
45 """A route entry describes a BGP route
46
47 i.e. the association of:
48 * a BGP NLRI of a specific type (e.g. a VPNv4 route
49 like "1.2.3.4:5:192.168.0.5/32")
50 * BGP attributes
51 * the source of the BGP route (e.g. the BGP peer, or the local VPN
52 instance, that advertizes the route)
53 """
54
55 def __init__(self, nlri, rts=None, attributes=None,
56 source=None):
57 if attributes is None:
58 attributes = exa.Attributes()
59 assert isinstance(attributes, exa.Attributes)
60 if rts is not None:
61 assert isinstance(rts, list)
62 assert len(rts) == 0 or isinstance(rts[0], exa.RouteTarget)
63
64 self.source = source
65 self.afi = nlri.afi
66 self.safi = nlri.safi
67 self.nlri = nlri
68 self.attributes = attributes
69 # a list of exa.bgp.message.update.attribute.community.
70 # extended.RouteTargetASN2Number
71 self._route_targets = []
72 if exa.Attribute.CODE.EXTENDED_COMMUNITY in self.attributes:
73 ecoms = self.attributes[
74 exa.Attribute.CODE.EXTENDED_COMMUNITY].communities
75 # use type(..) because isinstance(rtrecord, RouteTarget) is True
76 self._route_targets = [ecom for ecom in ecoms
77 if isinstance(ecom, exa.RouteTarget)]
78 if rts:
79 ecoms += rts
80 self._route_targets += rts
81 else:
82 if rts:
83 self.attributes.add(exa.ExtendedCommunities(rts))
84 self._route_targets += rts
85
86 @property
87 def route_targets(self):
88 return self._route_targets
89
90 def ecoms(self, filter_=None):
91 '''returns the route extended communities (+ optional filtering)'''
92 if filter_ is None:
93 def filter_real(ecom):
94 return True
95 elif isinstance(filter_, type):
96 def filter_real(ecom):
97 return isinstance(ecom, filter_)
98 else:
99 # filter is a function(ecom)
100 filter_real = filter_
101
102 if exa.Attribute.CODE.EXTENDED_COMMUNITY in self.attributes:
103 return list(
104 filter(filter_real,
105 self.attributes[exa.Attribute.CODE.EXTENDED_COMMUNITY]
106 .communities)
107 )
108 else:
109 return []
110
111 @log_decorator.log
112 def set_route_targets(self, route_targets):
113 # first build a list of ecoms without any RT
114 ecoms = self.ecoms(lambda ecom: not isinstance(ecom,
115 exa.RouteTarget))
116
117 # then add the right RTs
118 new_ecoms = exa.ExtendedCommunities()
119 new_ecoms.communities += ecoms
120 new_ecoms.communities += route_targets
121
122 # update
123 self._route_targets = route_targets
124
125 self.attributes.remove(new_ecoms.ID)
126 self.attributes.add(new_ecoms)
127
128 @property
129 def nexthop(self):
130 try:
131 return self.nlri.nexthop.top()
132 except AttributeError:
133 try:
134 return self.attributes[exa.Attribute.CODE.NEXT_HOP].top()
135 except KeyError:
136 return None
137
138 def __eq__(self, other):
139 if other is None:
140 return False
141 assert isinstance(other, RouteEntry)
142 return (self.afi == other.afi and
143 self.safi == other.safi and
144 self.source == other.source and
145 self.nlri == other.nlri and
146 self.attributes.sameValuesAs(other.attributes))
147
148 def __hash__(self):
149 return hash((self.afi, self.safi, str(self.source),
150 str(self.nexthop), self.nlri,
151 self.attributes))
152
153 def __repr__(self, skip_nexthop=False):
154 from_string = " from:%s" % self.source if self.source else ""
155
156 nexthop = ""
157 if not skip_nexthop:
158 nexthop = str(self.nexthop)
159
160 return "[RouteEntry: {}/{} {} nh:{} {}{}]".format(
161 self.afi, self.safi, self.nlri, nexthop,
162 self.attributes, from_string)
163
164 def get_lg_local_info(self, path_prefix):
165
166 att_dict = {}
167
168 for attribute in self.attributes.values():
169
170 # skip some attributes that we care less about
171 if attribute.ID in (exa.Attribute.CODE.AS_PATH,
172 exa.Attribute.CODE.ORIGIN):
173 continue
174
175 att_dict[
176 repr(exa.Attribute.CODE(attribute.ID))] = str(attribute)
177
178 res = {"afi-safi": "{}/{}".format(self.afi, self.safi),
179 "attributes": att_dict,
180 "next_hop": self.nexthop
181 }
182
183 if self.source:
184 res["source"] = {"id": self.source.name,
185 "href": lg.get_absolute_path("BGP_WORKERS",
186 path_prefix,
187 [self.source.name])
188 }
189
190 if self.safi in [exa.SAFI.mpls_vpn, exa.SAFI.evpn]:
191 res["route_targets"] = [str(rt) for rt in self.route_targets]
192
193 return {
194 repr(self.nlri): res
195 }
196
197
198 class RouteEvent:
199
200 """Represents an advertisement or withdrawal of a RouteEntry"""
201
202 # event Types
203 ADVERTISE = 1
204 WITHDRAW = 2
205
206 type2name = {ADVERTISE: "Advertise",
207 WITHDRAW: "Withdraw"}
208
209 def __init__(self, event_type, route_entry, source=None):
210 assert (event_type == RouteEvent.ADVERTISE or
211 event_type == RouteEvent.WITHDRAW)
212 assert isinstance(route_entry, RouteEntry)
213 self.type = event_type
214 self.route_entry = route_entry
215 if source is not None:
216 self.source = source
217 self.route_entry.source = source
218 else:
219 self.source = route_entry.source
220 assert self.source is not None
221 self.replaced_route = None
222
223 # this is required to overwrite the action field in an NLRI
224 # in the case where we generate a withdraw from an existing NLRI
225 # on a replaced route
226 # and this spares us the pain of specifying the action
227 # when creating an nlri
228 if event_type == RouteEvent.ADVERTISE:
229 self.route_entry.nlri.action = exa.OUT.ANNOUNCE
230 else: # WITHDRAW
231 self.route_entry.nlri.action = exa.OUT.WITHDRAW
232
233 @log_decorator.log
234 def set_replaced_route(self, replaced_route):
235 '''set_replaced_route hook for RouteTableManager
236
237 Called only by RouteTableManager.
238 replaced_route should be a RouteEntry
239 '''
240 assert (isinstance(replaced_route, RouteEntry) or
241 (replaced_route is None))
242 assert replaced_route != self.route_entry
243 self.replaced_route = replaced_route
244
245 def __repr__(self):
246 if self.replaced_route:
247 replaces_str = "replaces one route"
248 else:
249 replaces_str = "replaces no route"
250 return "[RouteEvent({}): {} {} {}]".format(replaces_str,
251 RouteEvent.type2name[
252 self.type],
253 self.route_entry,
254 self.source)
255
256
257 class UnsupportedRT(Exception):
258
259 def __init__(self, rt):
260 self.rt = rt
261
262
263 class _SubUnsubCommon:
264
265 def __init__(self, afi, safi, route_target, worker=None):
266 if not (route_target is None or
267 isinstance(route_target, exa.RouteTarget)):
268 raise UnsupportedRT(route_target)
269 self.afi = afi
270 self.safi = safi
271 self.route_target = route_target
272 self.worker = worker
273
274 def __repr__(self):
275 by_worker = " by %s" % self.worker.name if self.worker else ""
276 return "{} [{}/{},{}]{}".format(self.__class__.__name__,
277 self.afi or "*", self.safi or "*",
278 self.route_target or "*", by_worker)
279
280
281 class Subscription(_SubUnsubCommon):
282
283 """Represents a Subscription to RouteEvents
284
285 A subscription specifies the AFI, the SAFI, and the Route Target of the
286 RouteEntry for which the subscriber wants to receive events.
287
288 Any of these (afi, safi or route target) can be replaced by a wildcard:
289 * Subscription.ANY_AFI
290 * Subscription.ANY_SAFI
291 * Subscription.ANY_RT
292 """
293
294 ANY_AFI = None
295 ANY_SAFI = None
296 ANY_RT = None
297
298 def __init__(self, afi, safi, route_target=None, worker=None):
299 _SubUnsubCommon.__init__(self, afi, safi, route_target, worker)
300
301
302 class Unsubscription(_SubUnsubCommon):
303
304 def __init__(self, afi, safi, route_target=None, worker=None):
305 _SubUnsubCommon.__init__(self, afi, safi, route_target, worker)
306
307
308 class EventSource(lg.LookingGlassMixin):
309 '''Class for objects that advertise and withdraw routes
310
311 class needs to have a 'name' attribute
312 '''
313
314 def __init__(self, route_table_manager):
315 self.rtm = route_table_manager
316 # private data of RouteTableManager
317 self._rtm_route_entries = set()
318
319 def get_route_entries(self):
320 return self._rtm_route_entries
321
322 @log_decorator.log_info
323 def _advertise_route(self, route_entry):
324 LOG.debug("Publish advertise route event")
325 self.rtm.enqueue(RouteEvent(RouteEvent.ADVERTISE, route_entry, self))
326
327 @log_decorator.log_info
328 def _withdraw_route(self, route_entry):
329 LOG.debug("Publish withdraw route event")
330 self.rtm.enqueue(RouteEvent(RouteEvent.WITHDRAW, route_entry, self))
331
332 def get_lg_map(self):
333 return {
334 "adv_routes": (lg.SUBTREE, self.get_lg_routes)
335 }
336
337 def get_lg_routes(self, path_prefix):
338 return [route.get_looking_glass_info(path_prefix) for route in
339 self.get_route_entries()]
340
341
342 class WorkerCleanupEvent:
343
344 def __init__(self, worker):
345 self.worker = worker
346
347 def __repr__(self):
348 return "WorkerCleanupEvent:%s" % (self.worker.name)