This repository has been archived by the owner on Apr 22, 2024. It is now read-only.
/
controller.py
575 lines (469 loc) · 20.6 KB
/
controller.py
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
"""Kytos SDN Platform main class.
This module contains the main class of Kytos, which is
:class:`~.core.Controller`.
Basic usage:
.. code-block:: python3
from kytos.config import KytosConfig
from kytos.core import Controller
config = KytosConfig()
controller = Controller(config.options)
controller.start()
"""
import logging
import os
import re
import sys
from importlib.util import module_from_spec, spec_from_file_location
from threading import Thread
from kytos.core.api_server import APIServer
from kytos.core.buffers import KytosBuffers
from kytos.core.config import KytosConfig
from kytos.core.events import KytosEvent
from kytos.core.helpers import now
from kytos.core.logs import LogManager
from kytos.core.napps.manager import NAppsManager
from kytos.core.switch import Switch
from kytos.core.tcp_server import KytosOpenFlowRequestHandler, KytosServer
from kytos.core.websocket import LogWebSocket
__all__ = ('Controller',)
class Controller(object):
"""Main class of Kytos.
The main responsabilities of this class are:
- start a thread with :class:`~.core.tcp_server.KytosServer`;
- manage KytosNApps (install, load and unload);
- keep the buffers (instance of :class:`~.core.buffers.KytosBuffers`);
- manage which event should be sent to NApps methods;
- manage the buffers handlers, considering one thread per handler.
"""
def __init__(self, options=None):
"""Init method of Controller class.
Parameters:
options (ParseArgs.args): 'options' attribute from an instance of
KytosConfig class
"""
if options is None:
options = KytosConfig().options['daemon']
#: dict: keep the main threads of the controller (buffers and handler)
self._threads = {}
#: KytosBuffers: KytosBuffer object with Controller buffers
self.buffers = KytosBuffers()
#: dict: keep track of the socket connections labeled by ``(ip, port)``
#:
#: This dict stores all connections between the controller and the
#: switches. The key for this dict is a tuple (ip, port). The content
#: is another dict with the connection information.
self.connections = {}
#: dict: mapping of events and event listeners.
#:
#: The key of the dict is a KytosEvent (or a string that represent a
#: regex to match agains KytosEvents) and the value is a list of
#: methods that will receive the referenced event
self.events_listeners = {'kytos/core.connection.new':
[self.new_connection]}
#: dict: Current loaded apps - 'napp_name': napp (instance)
#:
#: The key is the napp name (string), while the value is the napp
#: instance itself.
self.napps = {}
#: Object generated by ParseArgs on config.py file
self.options = options
#: KytosServer: Instance of KytosServer that will be listening to TCP
#: connections.
self.server = None
#: dict: Current existing switches.
#:
#: The key is the switch dpid, while the value is a Switch object.
self.switches = {} # dpid: Switch()
self.started_at = None
self.websockets = {}
self.log = None
self.api_server = APIServer(__name__, self.options.debug)
#: Adding the napps 'enabled' directory into the PATH
#: Now you can access the enabled napps with:
#: from napps.<username>.<napp_name> import ?....
sys.path.append(os.path.join(self.options.napps, os.pardir))
def register_websockets(self):
"""Method used to register all websockets."""
log = LogWebSocket()
self.websockets['log'] = log
LogManager.add_stream_handler(log.stream)
self.api_server.register_websockets(self.websockets)
def enable_logs(self):
"""Method used to register kytos log and enable the logs."""
LogManager.load_logging_file(self.options.logging)
self.log = logging.getLogger(__name__)
def start(self):
"""Create pidfile and call start_controller method."""
self.enable_logs()
pid = os.getpid()
# Create directory if it does not exist.
os.makedirs(os.path.dirname(self.options.pidfile), exist_ok=True)
# Checks if a pidfile exists. Creates a new file.
try:
pidfile = open(self.options.pidfile, mode='x')
except OSError:
# This happens if there is a pidfile already.
# We shall check if the process that created the pidfile is still
# running.
try:
existing_file = open(self.options.pidfile, mode='r')
old_pid = int(existing_file.read())
os.kill(old_pid, 0)
# If kill() doesn't return an error, older instance is still
# running.
# Otherwise, overwrite the file and proceed.
self.log.info("Failed to create a pidfile. "
"Is kytos already running?")
self.log.info("Aborting")
exit(os.EX_CANTCREAT)
except OSError:
pidfile = open(self.options.pidfile, mode='w')
# Identifies the process that created the pidfile.
pidfile.write(str(pid))
pidfile.close()
self.start_controller()
def start_controller(self):
"""Start the controller.
Starts a thread with the KytosServer (TCP Server).
Starts a thread for each buffer handler.
Load the installed apps.
"""
self.api_server.register_kytos_routes()
self.api_server.register_web_ui()
self.register_websockets()
self.log.info("Starting Kytos - Kytos Controller")
self.server = KytosServer((self.options.listen,
int(self.options.port)),
KytosOpenFlowRequestHandler,
self)
raw_event_handler = self.raw_event_handler
msg_in_event_handler = self.msg_in_event_handler
msg_out_event_handler = self.msg_out_event_handler
app_event_handler = self.app_event_handler
thrds = {'tcp_server': Thread(name='TCP server',
target=self.server.serve_forever),
'api_server': Thread(name='API server',
target=self.api_server.run,
args=['0.0.0.0', 8181]),
'raw_event_handler': Thread(name='RawEvent Handler',
target=raw_event_handler),
'msg_in_event_handler': Thread(name='MsgInEvent Handler',
target=msg_in_event_handler),
'msg_out_event_handler': Thread(name='MsgOutEvent Handler',
target=msg_out_event_handler),
'app_event_handler': Thread(name='AppEvent Handler',
target=app_event_handler)}
self._threads = thrds
# This is critical, if any of them started we should exit.
for thread in self._threads.values():
try:
thread.start()
except OSError as e:
self.log.error("Error starting thread %s", thread)
self.log.error(e)
self.log.error("Kytos start aborted.")
sys.exit()
self.log.info("Loading Kytos NApps...")
self.load_napps()
self.started_at = now()
def register_rest_endpoint(self, *options, **kwargs):
"""Method used to return the endpoints registered by APIServer."""
self.api_server.register_rest_endpoint(*options, **kwargs)
def restart(self, graceful=True):
"""Restart Kytos SDN Controller.
Args:
graceful(bool): Represents the way that Kytos will restart.
"""
if self.started_at is not None:
self.stop(graceful)
self.__init__(self.options)
self.start()
def stop(self, graceful=True):
"""Method used to shutdown all services used by kytos.
This method should:
- stop all Websockets
- stop the API Server
- stop the Controller
"""
if self.started_at:
self.stop_controller(graceful)
def stop_controller(self, graceful=True):
"""Stop the controller.
This method should:
- announce on the network that the controller will shutdown;
- stop receiving incoming packages;
- call the 'shutdown' method of each KytosNApp that is running;
- finish reading the events on all buffers;
- stop each running handler;
- stop all running threads;
- remove the pidfile;
- stop the KytosServer;
"""
self.log.info("Stopping Kytos")
if not graceful:
self.server.socket.close()
self.server.shutdown()
self.buffers.send_stop_signal()
self.api_server.stop_api_server()
for thread in self._threads.values():
self.log.info("Stopping thread: %s", thread.name)
thread.join()
for thread in self._threads.values():
while thread.is_alive():
pass
self.started_at = None
self.unload_napps()
self.buffers = KytosBuffers()
try:
os.remove(self.options.pidfile)
except FileNotFoundError:
self.log.info("Could not find kytosd pid file.")
self.server.server_close()
def status(self):
"""Return status of Kytos Server.
If the controller kytos is running this method will be returned
"Running since 'Started_At'", otherwise "Stopped".
Returns:
status (string): String with kytos status.
"""
if self.started_at:
return "Running since %s" % self.started_at
return "Stopped"
def uptime(self):
"""Return the uptime of kytos server.
This method should return:
- 0 if Kytos Server is stopped.
- (kytos.start_at - datetime.now) if Kytos Server is running.
Returns:
interval (datetime.timedelta): The uptime interval
"""
return now() - self.started_at if self.started_at else 0
def notify_listeners(self, event):
"""Send the event to the specified listeners.
Loops over self.events_listeners matching (by regexp) the attribute
name of the event with the keys of events_listeners. If a match occurs,
then send the event to each registered listener.
Parameters:
event (KytosEvent): An instance of a KytosEvent.
"""
for event_regex, listeners in self.events_listeners.items():
if re.match(event_regex, event.name):
for listener in listeners:
listener(event)
def raw_event_handler(self):
"""Handle raw events.
This handler listen to the raw_buffer, get every event added to this
buffer and sends it to the listeners listening to this event.
It also verify if there is a switch instantiated on that connection_id
`(ip, port)`. If a switch was found, then the `connection_id` attribute
is set to `None` and the `dpid` is replaced with the switch dpid.
"""
self.log.info("Raw Event Handler started")
while True:
event = self.buffers.raw.get()
self.notify_listeners(event)
self.log.debug("Raw Event handler called")
if event.name == "kytos/core.shutdown":
self.log.debug("RawEvent handler stopped")
break
def msg_in_event_handler(self):
"""Handle msg_in events.
This handler listen to the msg_in_buffer, get every event added to this
buffer and sends it to the listeners listening to this event.
"""
self.log.info("Message In Event Handler started")
while True:
event = self.buffers.msg_in.get()
self.notify_listeners(event)
self.log.debug("MsgInEvent handler called")
if event.name == "kytos/core.shutdown":
self.log.debug("MsgInEvent handler stopped")
break
def msg_out_event_handler(self):
"""Handle msg_out events.
This handler listen to the msg_out_buffer, get every event added to
this buffer and sends it to the listeners listening to this event.
"""
self.log.info("Message Out Event Handler started")
while True:
triggered_event = self.buffers.msg_out.get()
if triggered_event.name == "kytos/core.shutdown":
self.log.debug("MsgOutEvent handler stopped")
break
message = triggered_event.content['message']
destination = triggered_event.destination
if destination:
destination.send(message.pack())
self.notify_listeners(triggered_event)
self.log.debug("MsgOutEvent handler called")
def app_event_handler(self):
"""Handle app events.
This handler listen to the app_buffer, get every event added to this
buffer and sends it to the listeners listening to this event.
"""
self.log.info("App Event Handler started")
while True:
event = self.buffers.app.get()
self.notify_listeners(event)
self.log.debug("AppEvent handler called")
if event.name == "kytos/core.shutdown":
self.log.debug("AppEvent handler stopped")
break
def get_switch_by_dpid(self, dpid):
"""Return a specific switch by dpid.
Parameters:
dpid (:class:`pyof.foundation.DPID`): dpid object used to identify
a switch.
Returns:
switch (:class:`~.core.switch.Switch`): Switch with dpid specified.
"""
return self.switches.get(dpid)
def get_switch_or_create(self, dpid, connection):
"""Return switch or create it if necessary.
Parameters:
dpid (:class:`pyof.foundation.DPID`): dpid object used to identify
a switch.
connection (:class:`~.core.switch.Connection`): connection used by
switch. If a switch has a connection that will be updated.
Returns:
switch (:class:`~.core.switch.Switch`): new or existent switch.
"""
self.create_or_update_connection(connection)
switch = self.get_switch_by_dpid(dpid)
event = None
if switch is None:
switch = Switch(dpid=dpid)
self.add_new_switch(switch)
event = KytosEvent(name='kytos/core.switches.new',
content={'switch': switch})
old_connection = switch.connection
switch.update_connection(connection)
if old_connection is not connection:
self.remove_connection(old_connection)
if event:
self.buffers.app.put(event)
return switch
def create_or_update_connection(self, connection):
"""Update a connection.
Parameters:
connection (:class:`~.core.switch.Connection`): Instance of
connection that will be updated.
"""
self.connections[connection.id] = connection
def get_connection_by_id(self, conn_id):
"""Return a existent connection by id.
Parameters:
id (int): id from a connection.
Returns:
connection (:class:`~.core.switch.Connection`): Instance of
connection or None Type.
"""
return self.connections.get(conn_id)
def remove_connection(self, connection):
"""Close a existent connection and remove it.
Parameters:
connection (:class:`~.core.switch.Connection`): Instance of
connection that
will be removed.
"""
if connection is None:
return False
try:
connection.close()
del self.connections[connection.id]
except KeyError:
return False
def remove_switch(self, switch):
"""Remove a existent switch.
Parameters:
switch (:class:`~.core.switch.Switch`): Instance of switch that
will be removed.
"""
try:
del self.switches[switch.dpid]
except KeyError:
return False
def new_connection(self, event):
"""Handle a kytos/core.connection.new event.
This method will read new connection event and store the connection
(socket) into the connections attribute on the controller.
It also clear all references to the connection since it is a new
connection on the same ip:port.
Parameters:
event (KytosEvent): The received event (kytos/core.connection.new)
with the needed infos.
"""
self.log.info("Handling KytosEvent:kytos/core.connection.new ...")
connection = event.source
# Remove old connection (aka cleanup) if exists
if self.get_connection_by_id(connection.id):
self.remove_connection(connection.id)
# Update connections with the new connection
self.create_or_update_connection(connection)
def add_new_switch(self, switch):
"""Add a new switch on the controller.
Parameters:
switch (Switch): A Switch object
"""
self.switches[switch.dpid] = switch
def load_napp(self, username, napp_name):
"""Load a single app.
Load a single NAPP based on its name.
Args:
username (str): NApp username present in napp's path.
napp_name (str): Name of the NApp to be loaded.
Raise:
FileNotFoundError: if napps' main.py is not found.
"""
if (username, napp_name) in self.napps:
message = 'NApp %s/%s was already loaded'
self.log.warning(message, username, napp_name)
else:
mod_name = '.'.join(['napps', username, napp_name, 'main'])
path = os.path.join(self.options.napps, username, napp_name,
'main.py')
napp_spec = spec_from_file_location(mod_name, path)
napp_module = module_from_spec(napp_spec)
sys.modules[napp_spec.name] = napp_module
napp_spec.loader.exec_module(napp_module)
napp = napp_module.Main(controller=self)
self.napps[(username, napp_name)] = napp
for event, listeners in napp._listeners.items(): # noqa
self.events_listeners.setdefault(event, []).extend(listeners)
napp.start()
def load_napps(self):
"""Load all NApps enabled on the NApps dir."""
napps = NAppsManager(self)
for napp in napps.list_enabled():
try:
self.log.info("Loading NApp %s", napp.id)
self.load_napp(napp.username, napp.name)
except FileNotFoundError as e:
self.log.error("Could not load NApp %s: %s", napp.id, e)
def unload_napp(self, username, napp_name):
"""Unload a specific NApp.
Args:
username (str): NApp username.
napp_name (str): Name of the NApp to be unloaded.
"""
napp = self.napps.pop((username, napp_name), None)
if napp is None:
self.log.warning('NApp %s/%s was not loaded', username, napp_name)
else:
self.log.info("Shutting down NApp %s/%s...", username, napp_name)
napp.shutdown()
# Removing listeners from that napp
for event_type, napp_listeners in napp._listeners.items(): # noqa
event_listeners = self.events_listeners[event_type]
for listener in napp_listeners:
event_listeners.remove(listener)
if not event_listeners:
del self.events_listeners[event_type]
def unload_napps(self):
"""Unload all loaded NApps that are not core NApps."""
# list() is used here to avoid the error:
# 'RuntimeError: dictionary changed size during iteration'
# This is caused by looping over an dictionary while removing
# items from it.
for (username, napp_name) in list(self.napps.keys()): # noqa
self.unload_napp(username, napp_name)