forked from martimy/flowmanager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflowmanager.py
558 lines (471 loc) · 19.4 KB
/
flowmanager.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
# Copyright (c) 2018 Maen Artimy
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ryu.base import app_manager
from ryu.app.wsgi import WSGIApplication
from ryu.controller import dpset
# these are needed for the events
from ryu.controller import ofp_event
from ryu.controller.handler import HANDSHAKE_DISPATCHER
from ryu.controller.handler import CONFIG_DISPATCHER
from ryu.controller.handler import MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_3
from ryu.lib import ofctl_v1_3
from ryu.lib import ofctl_utils
from ryu import utils
# for packet content
from ryu.lib.packet import packet
from ryu.lib.packet import ethernet
from ryu.lib.packet import ether_types
# for topology discovery
#from ryu.topology import event, switches
from ryu.topology.api import get_all_switch, get_all_link, get_all_host
from webapi import WebApi
import os, logging
from logging.handlers import WatchedFileHandler
class FlowManager(app_manager.RyuApp):
#OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]
_CONTEXTS = {'wsgi': WSGIApplication,
'dpset': dpset.DPSet}
port_id = {
"IN_PORT": 0xfffffff8,
"TABLE": 0xfffffff9,
"NORMAL": 0xfffffffa,
"FLOOD": 0xfffffffb,
"ALL": 0xfffffffc,
"CONTROLLER": 0xfffffffd,
"LOCAL": 0xfffffffe,
"ANY": 0xffffffff
}
logname = 'flwmgr'
logfile = 'flwmgr.log'
def __init__(self, *args, **kwargs):
super(FlowManager, self).__init__(*args, **kwargs)
wsgi = kwargs['wsgi']
self.dpset = kwargs['dpset']
# get this file's path
dirname = os.path.dirname(__file__)
self.lists = {}
self.lists['actions'] = self.read_files(
'actions', os.path.join(dirname, 'data/actions.txt'))
self.lists['matches'] = self.read_files(
'matches', os.path.join(dirname, 'data/matches.txt'))
self.waiters = {}
self.ofctl = ofctl_v1_3
# Data exchanged with WebApi
wsgi.register(WebApi,
{"webctl": self,
"dpset": self.dpset,
"lists": self.lists,
"waiters": self.waiters})
# Setup logging
self.logger = self.get_logger(self.logname, self.logfile, 'INFO', 0)
def get_logger(self, logname, logfile, loglevel, propagate):
"""Create and return a logger object."""
# TODO: simplify
logger = logging.getLogger(logname)
logger_handler = WatchedFileHandler(logfile, mode='w')
# removed \t%(name)-6s
log_fmt = '%(asctime)s\t%(levelname)-8s\t%(message)s'
logger_handler.setFormatter(
logging.Formatter(log_fmt, '%b %d %H:%M:%S'))
logger.addHandler(logger_handler)
logger.propagate = propagate
logger.setLevel(loglevel)
return logger
def get_switches(self):
"""Return switches."""
return self.dpset.get_all()
def get_switch_desc(self, dpid):
dp = self.dpset.get(dpid)
if dp:
return self.ofctl.get_desc_stats(dp, self.waiters, to_user=True)
else:
return None
def get_port_desc(self, dpid):
dp = self.dpset.get(dpid)
if dp:
return self.ofctl.get_port_desc(dp, self.waiters)
else:
return None
def get_port_stat(self, dpid):
dp = self.dpset.get(dpid)
if dp:
return self.ofctl.get_port_stats(dp, self.waiters, port=None, to_user=True)
return None
def get_flow_summary(self, dpid):
dp = self.dpset.get(dpid)
if dp:
return self.ofctl.get_aggregate_flow_stats(dp, self.waiters)
return None
def get_table_stat(self, dpid):
dp = self.dpset.get(dpid)
if dp:
return self.ofctl.get_table_stats(dp, self.waiters)
else:
return None
def read_logs(self):
items = []
with open(self.logfile, 'r') as my_file:
while True:
line = my_file.readline()
if not line:
break
lst = line.split('\t')
items.append(lst)
#items.append(line)
return items
def read_files(self, key, filename):
"""Reads tab-seperated text files.
Used to read files that contain data about match fields and actions.
"""
items = {}
with open(filename, 'r') as my_file:
while True:
line = my_file.readline()
if not line:
break
lst = line.split('\t')
items[lst[0]] = lst
return items
def get_actions(self, parser, set):
actions = []
aDict = {
'SET_FIELD': (parser.OFPActionSetField, 'field'),
'COPY_TTL_OUT': (parser.OFPActionCopyTtlOut, None),
'COPY_TTL_IN': (parser.OFPActionCopyTtlIn, None),
'POP_PBB': (parser.OFPActionPopPbb, None),
'PUSH_PBB': (parser.OFPActionPushPbb, 'ethertype'),
'POP_MPLS': (parser.OFPActionPopMpls, 'ethertype'),
'PUSH_MPLS': (parser.OFPActionPushMpls, 'ethertype'),
'POP_VLAN': (parser.OFPActionPopVlan, None),
'PUSH_VLAN': (parser.OFPActionPushVlan, 'ethertype'),
'DEC_MPLS_TTL': (parser.OFPActionDecMplsTtl, None),
'SET_MPLS_TTL': (parser.OFPActionSetMplsTtl, 'mpls_ttl'),
'DEC_NW_TTL': (parser.OFPActionDecNwTtl, None),
'SET_NW_TTL': (parser.OFPActionSetNwTtl, 'nw_ttl'),
'SET_QUEUE': (parser.OFPActionSetQueue, 'queue_id'),
'GROUP': (parser.OFPActionGroup, 'group_id'),
'OUTPUT': (parser.OFPActionOutput, 'port'),
}
for action in set:
key = action.keys()[0] #There should be only one key
value = action[key]
if key in aDict:
f = aDict[key][0] # the action
if aDict[key][1]: # check if the action needs a value
kwargs = {}
if aDict[key][1] == 'field':
x = value.split('=')
kwargs = {x[0]: x[1]}
elif aDict[key][1] == 'port':
x = value.upper()
val = self.port_id[x] if x in self.port_id else int(x)
kwargs = {aDict[key][1]: val}
else:
kwargs = {aDict[key][1]: int(value)}
actions.append(f(**kwargs))
else:
actions.append(f())
else:
raise Exception("Action {} not supported!".format(key))
return actions
def process_flow_message(self, d):
"""Sends flow form data to the switch to update flow tables.
"""
dp = self.dpset.get(d["dpid"])
if not dp:
return "Datapatch does not exist!"
ofproto = dp.ofproto
parser = dp.ofproto_parser
command = {
'add': ofproto.OFPFC_ADD,
'mod': ofproto.OFPFC_MODIFY,
'modst': ofproto.OFPFC_MODIFY_STRICT,
'del': ofproto.OFPFC_DELETE,
'delst': ofproto.OFPFC_DELETE_STRICT,
}
# Initialize arguments for the flow mod message
msg_kwargs = {
'datapath': dp,
'command': command.get(d["operation"], ofproto.OFPFC_ADD),
'buffer_id': ofproto.OFP_NO_BUFFER,
}
try:
msg_kwargs['table_id'] = d['table_id']
# Match fields
mf = d["match"]
match = parser.OFPMatch(**mf)
# print(match.to_jsondict())
msg_kwargs['match'] = match
# if d['hard_timeout'] else 0
msg_kwargs['hard_timeout'] = d['hard_timeout']
# if d['idle_timeout'] else 0
msg_kwargs['idle_timeout'] = d['idle_timeout']
msg_kwargs['priority'] = d['priority'] # if d['priority'] else 0
msg_kwargs['cookie'] = d['cookie'] # if d['cookie'] else 0
# if d['cookie_mask'] else 0
msg_kwargs['cookie_mask'] = d['cookie_mask']
# d['out_port'] # for the delete command
msg_kwargs['out_port'] = d['out_port'] if d['out_port'] >= 0 else ofproto.OFPP_ANY
# d['out_group'] # for the delete command
msg_kwargs['out_group'] = d['out_group'] if d['out_group'] >= 0 else ofproto.OFPG_ANY
# instructions
inst = []
# Goto meter
if d["meter_id"]:
inst += [parser.OFPInstructionMeter(d["meter_id"])]
# Apply Actions
if d["apply"]:
applyActions = self.get_actions(parser, d["apply"])
inst += [parser.OFPInstructionActions(
ofproto.OFPIT_APPLY_ACTIONS, applyActions)]
# Clear Actions
if d["clearactions"]:
inst += [parser.OFPInstructionActions(
ofproto.OFPIT_CLEAR_ACTIONS, [])]
# Write Actions
if d["write"]:
# bc actions must be unique they are in dict
# from dict to list
toList = [{k:d["write"][k]} for k in d["write"]]
#print(toList)
writeActions = self.get_actions(parser, toList)
inst += [parser.OFPInstructionActions(
ofproto.OFPIT_WRITE_ACTIONS, writeActions)]
# Write Metadata
if d["metadata"]:
inst += [parser.OFPInstructionWriteMetadata(
d["metadata"], d["metadata_mask"])]
# Goto Table Metadata
if d["goto"]:
inst += [parser.OFPInstructionGotoTable(table_id=d["goto"])]
if inst:
msg_kwargs['instructions'] = inst
# Flags
flags = 0
flags += 0x01 if d['SEND_FLOW_REM'] else 0
flags += 0x02 if d['CHECK_OVERLAP'] else 0
flags += 0x04 if d['RESET_COUNTS'] else 0
flags += 0x08 if d['NO_PKT_COUNTS'] else 0
flags += 0x10 if d['NO_BYT_COUNTS'] else 0
msg_kwargs['flags'] = flags
except Exception as e:
return "Value for '{}' is not found!".format(e.message)
# ryu/ryu/ofproto/ofproto_v1_3_parser.py
msg = parser.OFPFlowMod(**msg_kwargs)
try:
dp.send_msg(msg) # ryu/ryu/controller/controller.py
except KeyError as e:
return e.__repr__()
except Exception as e:
return e.__repr__()
return "Message sent successfully."
def process_group_message(self, d):
"""Sends group form data to the switch to update group tables.
"""
dp = self.dpset.get(d["dpid"])
if not dp:
return "Datapatch does not exist!"
ofproto = dp.ofproto
parser = dp.ofproto_parser
command = {
'add': ofproto.OFPGC_ADD,
'mod': ofproto.OFPGC_MODIFY,
'del': ofproto.OFPGC_DELETE,
}
cmd = command.get(d["operation"], ofproto.OFPGC_ADD)
type_convert = {'ALL': dp.ofproto.OFPGT_ALL,
'SELECT': dp.ofproto.OFPGT_SELECT,
'INDIRECT': dp.ofproto.OFPGT_INDIRECT,
'FF': dp.ofproto.OFPGT_FF}
gtype = type_convert.get(d["type"])
group_id = d["group_id"]
buckets = []
for bucket in d["buckets"]:
#print("bucket", bucket)
weight = bucket.get('weight', 0)
watch_port = bucket.get('watch_port', ofproto.OFPP_ANY)
watch_group = bucket.get('watch_group', dp.ofproto.OFPG_ANY)
actions = []
if bucket['actions']:
actions = self.get_actions(parser, bucket['actions'])
buckets.append(dp.ofproto_parser.OFPBucket(
weight, watch_port, watch_group, actions))
#print(dp, cmd, gtype, group_id, buckets)
group_mod = parser.OFPGroupMod(
dp, cmd, gtype, group_id, buckets)
try:
dp.send_msg(group_mod) # ryu/ryu/controller/controller.py
except KeyError as e:
return e.__repr__()
except Exception as e:
return e.__repr__()
return "Message sent successfully."
def process_meter_message(self, d):
"""Sends meter form data to the switch to update meter table.
"""
dp = self.dpset.get(d["dpid"])
if not dp:
return "Datapatch does not exist!"
ofproto = dp.ofproto
parser = dp.ofproto_parser
command = {
'add': ofproto.OFPMC_ADD,
'mod': ofproto.OFPMC_MODIFY,
'del': ofproto.OFPMC_DELETE,
}
cmd = command.get(d["operation"], ofproto.OFPMC_ADD)
meter_id = d["meter_id"]
# Flags
flags = 0
flags += 0x01 if d['OFPMF_KBPS'] else 0
flags += 0x02 if d['OFPMF_PKTPS'] else 0
flags += 0x04 if d['OFPMF_BURST'] else 0
flags += 0x08 if d['OFPMF_STATS'] else 0
bands = []
for band in d["bands"]:
#mtype = type_convert.get(band[0])
if band[0] == 'DROP':
bands += [parser.OFPMeterBandDrop(rate=band[1],
burst_size=band[2])]
elif band[0] == 'DSCP_REMARK':
bands += [parser.OFPMeterBandDscpRemark(rate=band[1],
burst_size=band[2], prec_level=band[3])]
print(dp, cmd, flags, meter_id, bands)
meter_mod = parser.OFPMeterMod(dp, cmd, flags, meter_id, bands)
try:
dp.send_msg(meter_mod)
except KeyError as e:
return e.__repr__()
except Exception as e:
return e.__repr__()
return "Message sent successfully."
# def get_flow_stats(self, req, dpid): # unused
# flow = {} # no filters
# dp = self.dpset.get(int(str(dpid), 0))
# return self.ofctl.get_flow_stats(dp, self.waiters, flow)
def get_stats(self, req, dpid):
dp = self.dpset.get(int(str(dpid), 0))
if req == "flows":
return self.ofctl.get_flow_stats(dp, self.waiters)
elif req == "groups":
return {"desc": self.ofctl.get_group_desc(dp, self.waiters),
"stats": self.ofctl.get_group_stats(dp, self.waiters)}
elif req == "meters":
return {"desc": self.ofctl.get_meter_config(dp, self.waiters),
"stats": self.ofctl.get_meter_stats(dp, self.waiters)}
def get_packet_summary(self, content):
pkt = packet.Packet(content)
eth = pkt.get_protocols(ethernet.ethernet)[0]
ethtype = eth.ethertype
dst = eth.dst
src = eth.src
return '(src={}, dst={}, type=0x{:04x})'.format(src, dst, ethtype)
##### Event Handlers #######################################
@set_ev_cls([ # ofp_event.EventOFPStatsReply,
ofp_event.EventOFPDescStatsReply,
ofp_event.EventOFPFlowStatsReply,
ofp_event.EventOFPAggregateStatsReply,
ofp_event.EventOFPTableStatsReply,
# ofp_event.EventOFPTableFeaturesStatsReply,
ofp_event.EventOFPPortStatsReply,
# ofp_event.EventOFPQueueStatsReply,
# ofp_event.EventOFPQueueDescStatsReply,
ofp_event.EventOFPMeterStatsReply,
# ofp_event.EventOFPMeterFeaturesStatsReply,
ofp_event.EventOFPMeterConfigStatsReply,
ofp_event.EventOFPGroupStatsReply,
# ofp_event.EventOFPGroupFeaturesStatsReply,
ofp_event.EventOFPGroupDescStatsReply,
ofp_event.EventOFPPortDescStatsReply,
# ofp_event.EventOFPPacketIn,
], MAIN_DISPATCHER)
def stats_reply_handler(self, ev):
msg = ev.msg
dp = msg.datapath
if dp.id not in self.waiters:
return
if msg.xid not in self.waiters[dp.id]:
return
lock, msgs = self.waiters[dp.id][msg.xid]
msgs.append(msg)
flags = dp.ofproto.OFPMPF_REPLY_MORE
if msg.flags & flags:
return
del self.waiters[dp.id][msg.xid]
lock.set()
# self.messages.append(msg)
@set_ev_cls(ofp_event.EventOFPFlowRemoved, MAIN_DISPATCHER)
def flow_removed_handler(self, ev):
msg = ev.msg
dp = msg.datapath
ofp = dp.ofproto
if msg.reason == ofp.OFPRR_IDLE_TIMEOUT:
reason = 'IDLE TIMEOUT'
elif msg.reason == ofp.OFPRR_HARD_TIMEOUT:
reason = 'HARD TIMEOUT'
elif msg.reason == ofp.OFPRR_DELETE:
reason = 'DELETE'
elif msg.reason == ofp.OFPRR_GROUP_DELETE:
reason = 'GROUP DELETE'
else:
reason = 'unknown'
self.logger.info('FlowRemoved\t'
'cookie=%d priority=%d reason=%s table_id=%d '
'duration_sec=%d duration_nsec=%d '
'idle_timeout=%d hard_timeout=%d '
'packet_count=%d byte_count=%d match.fields=%s',
msg.cookie, msg.priority, reason, msg.table_id,
msg.duration_sec, msg.duration_nsec,
msg.idle_timeout, msg.hard_timeout,
msg.packet_count, msg.byte_count, msg.match)
@set_ev_cls(ofp_event.EventOFPErrorMsg,
[HANDSHAKE_DISPATCHER, CONFIG_DISPATCHER, MAIN_DISPATCHER])
def error_msg_handler(self, ev):
msg = ev.msg
self.logger.error('ErrorMsg\ttype=0x%02x code=0x%02x '
'message=%s',
msg.type, msg.code, utils.hex_array(msg.data))
@set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
def packet_in_handler(self, ev):
msg = ev.msg
dp = msg.datapath
ofp = dp.ofproto
if msg.reason == ofp.OFPR_NO_MATCH:
reason = 'NO MATCH'
elif msg.reason == ofp.OFPR_ACTION:
reason = 'ACTION'
elif msg.reason == ofp.OFPR_INVALID_TTL:
reason = 'INVALID TTL'
else:
reason = 'UNKNOWN'
self.logger.info('PacketIn\t'
'buffer_id=%x total_len=%d reason=%s '
'table_id=%d cookie=%d match=%s summary=%s',
msg.buffer_id, msg.total_len, reason,
msg.table_id, msg.cookie, msg.match,
#utils.hex_array(msg.data))
self.get_packet_summary(msg.data))
# @set_ev_cls(event.EventSwitchEnter)
def get_topology_data(self):
"""Get Topology Data
"""
switch_list = get_all_switch(self)
switches = [switch.to_dict() for switch in switch_list]
links_list = get_all_link(self)
links = [link.to_dict() for link in links_list]
host_list = get_all_host(self)
hosts = [h.to_dict() for h in host_list]
return {"switches": switches, "links":links, "hosts": hosts}