Debian Codegraph @

networking_bagpipe/bagpipe_bgp/engine/bgp_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 abc
16 import random
17 import threading
18 import time
19
20 from oslo_log import log as logging
21
22 from networking_bagpipe._i18n import _
23 from networking_bagpipe.bagpipe_bgp.common import looking_glass as lg
24 from networking_bagpipe.bagpipe_bgp import engine
25 from networking_bagpipe.bagpipe_bgp.engine import worker
26
27
28 INIT = "Init-Event"
29 CONNECT_NOW = "Connect-Now"
30 SEND_KEEP_ALIVE = "Send-KeepAlive"
31 KEEP_ALIVE_RECEIVED = "KeepAlive-received"
32
33 DEFAULT_HOLDTIME = 180
34
35 ERROR_RETRY_TIMER = 20
36 KA_EXPIRY_RETRY_TIMER = 5
37 CONNECT_RETRY_TIMER = 5
38
39
40 class FSM:
41
42 '''Represents the state of the BGP Finite State Machine'''
43
44 Idle = "Idle"
45 Connect = 'Connect'
46 OpenSent = 'OpenSent'
47 OpenConfirm = 'OpenConfirm'
48 Active = 'Active'
49 Established = 'Established'
50
51 def __init__(self, worker):
52 self.worker = worker
53 self._state = FSM.Idle
54 self._prev_state = None
55 self.all_states = [FSM.Idle, FSM.Connect, FSM.OpenSent,
56 FSM.OpenConfirm, FSM.Active, FSM.Established]
57 self.last_transition_time = time.time()
58
59 @property
60 def state(self):
61 return self._state
62
63 @property
64 def previous_state(self):
65 return self._prev_state
66
67 @state.setter
68 def state(self, state):
69 if state == self._state:
70 return
71 if state in self.all_states:
72 self._prev_state = self._state
73 self._state = state
74 self.last_transition_time = time.time()
75 self.worker.log.info(
76 "%s BGP FSM transitioned from '%s' to '%s' state" %
77 (self.worker, self._prev_state, self._state))
78 else:
79 raise Exception(_("no such state (%s)" % repr(state)))
80
81 def __repr__(self):
82 return self._state
83
84
85 class StoppedException(Exception):
86 pass
87
88
89 class InitiateConnectionException(Exception):
90 pass
91
92
93 class OpenWaitTimeout(Exception):
94 pass
95
96
97 class ToIdle:
98
99 def __init__(self, delay):
100 # add 50% random delay to avoid reconnect bursts
101 self.delay = delay * random.uniform(1, 1.5)
102
103 def __repr__(self):
104 return "ToIdle(%s)" % self.delay
105
106
107 class BGPPeerWorker(worker.Worker,
108 threading.Thread,
109 lg.LookingGlassLocalLogger,
110 metaclass=abc.ABCMeta):
111
112 '''Partially abstract class for a Worker implementing the BGP protocol.'''
113
114 def __init__(self, bgp_manager, peer_address):
115 # call super
116 threading.Thread.__init__(self)
117 self.setDaemon(True)
118 worker.Worker.__init__(self, bgp_manager, "BGP-%s" % peer_address)
119
120 self.peer_address = peer_address
121
122 # its up to subclasses to call _set_hold_time again to set holdtime
123 # based on value advertized by peer
124 self._set_hold_time(DEFAULT_HOLDTIME)
125
126 # used to stop receive_thread
127 self._stop_loops = threading.Event()
128 # used to track that we've been told to stop:
129 self.should_stop = False
130
131 self.send_ka_timer = None
132 self.ka_reception_timer = None
133
134 lg.LookingGlassLocalLogger.__init__(self,
135 self.peer_address.replace(".",
136 "-"))
137
138 self.fsm = FSM(self)
139
140 self.log.debug("INIT %s", self.name)
141 self.enqueue(CONNECT_NOW)
142
143 def stop(self):
144 super().stop()
145 self.should_stop = True
146 self._stop_and_clean()
147
148 def _set_hold_time(self, holdtime):
149 '''sets the session holdtime
150
151 holdtime in seconds
152 keepalive expected, or sent, every holdtime/3 second
153 '''
154 assert holdtime > 30
155 self.kat_period = int(holdtime / 3.0)
156 self.kat_expiry_time = self.kat_period * 3
157
158 # called by _event_queue_processor_loop
159 def _on_event(self, event):
160
161 self.log.debug("event: %s", event)
162
163 if event == CONNECT_NOW:
164 self._connect()
165
166 elif isinstance(event, ToIdle):
167 self._to_idle(event.delay)
168
169 elif isinstance(event, engine.RouteEvent):
170 if self.fsm.state == FSM.Established:
171 self._send(self._update_for_route_event(event))
172 else:
173 raise Exception(_("cannot process event in '%s' state"
174 % self.fsm.state))
175
176 elif event == SEND_KEEP_ALIVE:
177 self._send(self._keep_alive_message_data())
178
179 elif event == KEEP_ALIVE_RECEIVED:
180 self.on_keep_alive_received()
181
182 else:
183 self.log.warning("event not processed: %s", event)
184
185 def _stopped(self):
186 self.fsm.state = FSM.Idle
187
188 def _connect(self):
189 self._reset_local_lg_logs()
190
191 # initiate connection
192 self.log.debug("connecting now")
193
194 self.fsm.state = FSM.Connect
195
196 try:
197 self._initiate_connection()
198 except (InitiateConnectionException, OpenWaitTimeout) as e:
199 self.log.warning("%s while initiating connection: %s",
200 e.__class__.__name__, e)
201 self._to_active()
202 return
203 except StoppedException:
204 self.log.info("Thread stopped during connection init")
205 return
206 except Exception as e:
207 self.log.warning("Exception while initiating connection: %s", e)
208 if self.log.isEnabledFor(logging.DEBUG):
209 self.log.exception("")
210 self._to_active()
211 return
212
213 self._stop_loops.clear()
214
215 self.init_send_keep_alive_timer()
216 self.init_keep_alive_reception_timer()
217
218 # spawns a receive thread
219 self.receive_thread = threading.Thread(target=self._receive_loop,
220 name=("%s:receive_loop" %
221 self.name))
222 self.receive_thread.start()
223
224 self._to_established()
225
226 def _to_active(self):
227 self.fsm.state = FSM.Active
228 self._stop_and_clean()
229 self.init_connect_timer(CONNECT_RETRY_TIMER)
230
231 def _to_established(self):
232 self.fsm.state = FSM.Established
233
234 def _to_idle(self, delay_before_connect=0):
235 self.fsm.state = FSM.Idle
236 self._stop_and_clean()
237
238 if delay_before_connect:
239 self.init_connect_timer(delay_before_connect)
240 else:
241 self.enqueue(CONNECT_NOW)
242
243 def _stop_and_clean(self):
244 self._stop_loops.set()
245
246 if self.send_ka_timer:
247 self.send_ka_timer.cancel()
248 if self.ka_reception_timer:
249 self.ka_reception_timer.cancel()
250
251 self._cleanup()
252
253 def is_established(self):
254 return self.fsm.state == FSM.Established
255
256 def _receive_loop(self):
257 self.log.info("Start receive loop")
258 self._stop_loops.clear()
259 while not self._stop_loops.isSet():
260 try:
261 loop_result = self._receive_loop_fun()
262 if loop_result == 0:
263 self.log.info("receive_loop_fun returned 0, aborting")
264 break
265 elif loop_result == 2:
266 self.log.warning("receive_loop_fun returned 2 (error), "
267 "aborting receive_loop and reinit'ing")
268 # FIXME: use (Worker.)enqueue_high_priority so that
269 # ToIdle is treated before other events
270 self.enqueue(ToIdle(ERROR_RETRY_TIMER))
271 break
272 else:
273 # everything went fine
274 pass
275 except Exception as e:
276 self.log.error("Error: %s (=> aborting receive_loop and "
277 "reinitializing)", e)
278 if self.log.isEnabledFor(logging.WARNING):
279 self.log.exception("")
280 # FIXME: use (Worker.)enqueue_high_priority so that
281 # ToIdle is treated before other events
282 self.enqueue(ToIdle(ERROR_RETRY_TIMER))
283 break
284
285 self.log.info("End receive loop")
286
287 # Connect retry timer #####
288 def init_connect_timer(self, delay):
289 self.log.debug("INIT connect timer (%ds)", delay)
290 self.connect_timer = threading.Timer(delay, self.enqueue,
291 [CONNECT_NOW])
292 self.connect_timer.name = "%s:connect_timer" % self.name
293 self.connect_timer.start()
294
295 # Sending keep-alive's #####
296
297 def init_send_keep_alive_timer(self):
298 self.log.debug("INIT Send Keepalive timer (%ds)", self.kat_period)
299 self.send_ka_timer = threading.Timer(self.kat_period,
300 self.send_keep_alive_trigger)
301 self.send_ka_timer.name = "%s:send_ka_timer" % self.name
302 self.send_ka_timer.start()
303
304 def send_keep_alive_trigger(self):
305 self.log.debug("Trigger to send Keepalive")
306 self.enqueue(SEND_KEEP_ALIVE)
307 self.init_send_keep_alive_timer()
308
309 # Receiving keep-alive's #####
310
311 def init_keep_alive_reception_timer(self):
312 self.log.debug(
313 "INIT Keepalive reception timer (%ds)", self.kat_expiry_time)
314 self.ka_reception_timer = threading.Timer(
315 self.kat_expiry_time,
316 self.enqueue,
317 [ToIdle(KA_EXPIRY_RETRY_TIMER)])
318 self.ka_reception_timer.start()
319
320 def on_keep_alive_received(self):
321 self.log.debug("Keepalive received")
322 self.ka_reception_timer.cancel()
323 self.init_keep_alive_reception_timer()
324
325 # Abstract methods
326
327 @abc.abstractmethod
328 def _initiate_connection(self):
329 '''Abstract method to initiate a connection
330
331 The implementation will initiated the connection to the BGP peer, do
332 the initial BGP handshake (send Open, receive Open, send first
333 KeepAlive, receive first KeepAlive) and track the intermediate
334 FSM states (OpenSent, OpenConfirm).
335 '''
336 pass
337
338 @abc.abstractmethod
339 def _receive_loop_fun(self):
340 '''abstract method for internal receive loop
341
342 Return codes:
343 - 0: we decided to stop based on stop_loops being set
344 - 1: everything went fine, pursue
345 - 2: there was an error
346 '''
347 pass
348
349 @abc.abstractmethod
350 def _keep_alive_message_data(self):
351 pass
352
353 @abc.abstractmethod
354 def _send(self, data):
355 pass
356
357 @abc.abstractmethod
358 def _update_for_route_event(self, event):
359 pass
360
361 # Looking glass hooks ###
362
363 def get_lg_local_info(self, path_prefix):
364 return {
365 "protocol": {
366 "state": self.fsm.state,
367 "previous_state": "(%s)" % self.fsm.previous_state,
368 "hold_time": self.kat_expiry_time,
369 "last_transition_time": time.strftime(
370 '%Y-%m-%d %H:%M:%S',
371 time.localtime(self.fsm.last_transition_time))
372 }
373 }