-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathl3-qos.py
executable file
·438 lines (367 loc) · 16 KB
/
l3-qos.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
# Copyright 2012-2013 James McCauley
#
# 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.
#Modulo l3_learning com aplicacao de QoS
"""
A stupid L3 switch
For each switch:
1) Keep a table that maps IP addresses to MAC addresses and switch ports.
Stock this table using information from ARP and IP packets.
2) When you see an ARP query, try to answer it using information in the table
from step 1. If the info in the table is old, just flood the query.
3) Flood all other ARPs.
4) When you see an IP packet, if you know the destination port (because it's
in the table from step 1), install a flow for it.
"""
from pox.core import core
import pox
log = core.getLogger()
from pox.lib.packet.ethernet import ethernet, ETHER_BROADCAST
from pox.lib.packet.ipv4 import ipv4
from pox.lib.packet.arp import arp
from pox.lib.addresses import IPAddr, EthAddr
from pox.lib.util import str_to_bool, dpid_to_str
from pox.lib.recoco import Timer
import pox.openflow.libopenflow_01 as of
from pox.lib.revent import *
import time
import os
import pickle
# Timeout for flows
FLOW_IDLE_TIMEOUT = 30 #IDLE_TIMEOUT alterado de 10 para 30
# Timeout for ARP entries
ARP_TIMEOUT = 60 * 2
# Maximum number of packet to buffer on a switch for an unknown IP
MAX_BUFFERED_PER_IP = 5
# Maximum time to hang on to a buffer for an unknown IP in seconds
MAX_BUFFER_TIME = 5
##### Porta do prestador
SERVER_PORT = 23000
##### Vazao maxima da rede (bps)
TX_MAX = 1000000000
##### Arquivo e variaveis de lista de objetos Classe
filename=os.getenv("HOME")+'/pox/ext/classes.conf'
global classlist
global be
class Entry (object):
"""
Not strictly an ARP entry.
We use the port to determine which port to forward traffic out of.
We use the MAC to answer ARP replies.
We use the timeout so that if an entry is older than ARP_TIMEOUT, we
flood the ARP request rather than try to answer it ourselves.
"""
def __init__ (self, port, mac):
self.timeout = time.time() + ARP_TIMEOUT
self.port = port
self.mac = mac
def __eq__ (self, other):
if type(other) == tuple:
return (self.port,self.mac)==other
else:
return (self.port,self.mac)==(other.port,other.mac)
def __ne__ (self, other):
return not self.__eq__(other)
def isExpired (self):
if self.port == of.OFPP_NONE: return False
return time.time() > self.timeout
def dpid_to_mac (dpid):
return EthAddr("%012x" % (dpid & 0xffFFffFFffFF,))
#####Carregamento da lista de objetos Classe
def loadClass():
global classlist
global be
if os.path.isfile(filename):
filec = open(filename,'rb')
classlist = pickle.load(filec)
filec.close()
be = classlist[0].pico
class l3_switch (EventMixin):
def __init__ (self, fakeways = [], arp_for_unknowns = False):
# These are "fake gateways" -- we'll answer ARPs for them with MAC
# of the switch they're connected to.
self.fakeways = set(fakeways)
# If this is true and we see a packet for an unknown
# host, we'll ARP for it.
self.arp_for_unknowns = arp_for_unknowns
# (dpid,IP) -> expire_time
# We use this to keep from spamming ARPs
self.outstanding_arps = {}
# (dpid,IP) -> [(expire_time,buffer_id,in_port), ...]
# These are buffers we've gotten at this datapath for this IP which
# we can't deliver because we don't know where they go.
self.lost_buffers = {}
# For each switch, we map IP addresses to Entries
self.arpTable = {}
# This timer handles expiring stuff
self._expire_timer = Timer(5, self._handle_expiration, recurring=True)
self.listenTo(core)
##### Inclusao de dicionario de mapeamento de IP, porta e fila de QoS
self.portMap = {}
##### Inclusao de dicionario de registro de disponibilidade de QoS em cada enlace de cada switch
self.hasQoS = {}
def _handle_expiration (self):
# Called by a timer so that we can remove old items.
empty = []
for k,v in self.lost_buffers.iteritems():
dpid,ip = k
for item in list(v):
expires_at,buffer_id,in_port = item
if expires_at < time.time():
# This packet is old. Tell this switch to drop it.
v.remove(item)
po = of.ofp_packet_out(buffer_id = buffer_id, in_port = in_port)
core.openflow.sendToDPID(dpid, po)
if len(v) == 0: empty.append(k)
# Remove empty buffer bins
for k in empty:
del self.lost_buffers[k]
def _send_lost_buffers (self, dpid, ipaddr, macaddr, port):
"""
We may have "lost" buffers -- packets we got but didn't know
where to send at the time. We may know now. Try and see.
"""
if (dpid,ipaddr) in self.lost_buffers:
# Yup!
bucket = self.lost_buffers[(dpid,ipaddr)]
del self.lost_buffers[(dpid,ipaddr)]
log.debug("Sending %i buffered packets to %s from %s"
% (len(bucket),ipaddr,dpid_to_str(dpid)))
for _,buffer_id,in_port in bucket:
po = of.ofp_packet_out(buffer_id=buffer_id,in_port=in_port)
po.actions.append(of.ofp_action_dl_addr.set_dst(macaddr))
po.actions.append(of.ofp_action_output(port = port))
core.openflow.sendToDPID(dpid, po)
def _handle_GoingUpEvent (self, event):
self.listenTo(core.openflow)
log.info("Up...")
#Chama a funcao de carregamento de lista de objetos Classe
loadClass()
log.info("Carregada lista de classes de servico...")
def _handle_PacketIn (self, event):
dpid = event.connection.dpid
inport = event.port
packet = event.parsed
if not packet.parsed:
log.warning("%i %i ignoring unparsed packet", dpid, inport)
return
if dpid not in self.arpTable:
# New switch -- create an empty table
self.arpTable[dpid] = {}
##### Cria uma tabela vazia para registro de disponibilidade de QoS
self.hasQoS[dpid] = {}
for fake in self.fakeways:
self.arpTable[dpid][IPAddr(fake)] = Entry(of.OFPP_NONE,
dpid_to_mac(dpid))
if packet.type == ethernet.LLDP_TYPE:
# Ignore LLDP packets
return
if isinstance(packet.next, ipv4):
log.debug("%i %i IP %s => %s", dpid,inport,
packet.next.srcip,packet.next.dstip)
# Send any waiting packets...
self._send_lost_buffers(dpid, packet.next.srcip, packet.src, inport)
# Learn or update port/MAC info
if packet.next.srcip in self.arpTable[dpid]:
if self.arpTable[dpid][packet.next.srcip] != (inport, packet.src):
log.info("%i %i RE-learned %s", dpid,inport,packet.next.srcip)
else:
log.debug("%i %i learned %s", dpid,inport,str(packet.next.srcip))
self.arpTable[dpid][packet.next.srcip] = Entry(inport, packet.src)
# Try to forward
dstaddr = packet.next.dstip
if dstaddr in self.arpTable[dpid]:
# We have info about what port to send it out on...
prt = self.arpTable[dpid][dstaddr].port
mac = self.arpTable[dpid][dstaddr].mac
if prt == inport:
log.warning("%i %i not sending packet for %s back out of the " +
"input port" % (dpid, inport, str(dstaddr)))
else:
log.debug("%i %i installing flow for %s => %s out port %i"
% (dpid, inport, packet.next.srcip, dstaddr, prt))
actions = []
actions.append(of.ofp_action_dl_addr.set_dst(mac))
actions.append(of.ofp_action_output(port = prt))
match = of.ofp_match.from_packet(packet, inport)
match.dl_src = None # Wildcard source MAC
msg = of.ofp_flow_mod(command=of.OFPFC_ADD,
idle_timeout=FLOW_IDLE_TIMEOUT,
hard_timeout=of.OFP_FLOW_PERMANENT,
buffer_id=event.ofp.buffer_id,
actions=actions,
match=of.ofp_match.from_packet(packet,
inport))
event.connection.send(msg.pack())
##########################################################################################################
########################################### Instrucoes QoS ###############################################
##########################################################################################################
net=packet.next
transp=packet.next.next
#Realiza o mapeamento inicial entre IP, porta e QoS (-1)
if net.protocol==6 and transp.dstport==SERVER_PORT:
if not self.portMap.has_key(net.srcip):
self.portMap={net.srcip:(transp.srcport,-1)}
#Testa se o pacote eh UDP (troca de mensagens RSVP)
if net.protocol==17:
#Testa se a mensagem eh RSVP originada pelo solicitador
if transp.srcport==23231:
#Testa se a mensagem eh RSVP RESV
if net.tos!=0:
#Atualiza a fila do mapeamento IP, porta e QoS
port,queue=self.portMap[net.srcip]
queue=(net.tos/10)-1
self.portMap[net.srcip]=(port,queue)
#Consulta a disponibilidade de QoS na porta de saida do roteador
if not self.hasQoS[dpid].has_key(inport):
self.hasQoS[dpid][inport] = be
if self.hasQoS[dpid][inport] + classlist[queue].pico <= TX_MAX:
log.info("QoS disponivel em R%d - porta %d: %d",dpid,inport,TX_MAX-self.hasQoS[dpid][inport])
else:
log.info("QoS nao disponivel - largura de banda insuficiente")
#Testa se a mensagem eh RSVP FIN
else:
#Exclui o mapeamento IP, porta e QoS
if self.portMap.has_key(net.srcip):
del self.portMap[net.srcip]
#Testa se a mensagem eh RSVP originada pelo prestador
if transp.srcport==23232:
#Testa se a mensagem eh RSVP RESV_CONF
if net.tos!=0:
port,queue=self.portMap[net.dstip]
#Aplica QoS na porta de saida do roteador
qos=os.popen("ovs-vsctl list qos | grep _uuid | awk '{print $3}'").read().strip('\n')
os.system('ovs-vsctl set port r%d-eth%d qos=%s' %(dpid,prt,qos))
log.info("QoS %s aplicada em R%s - porta %d",qos,dpid,prt)
#Acrescenta a banda alocada a tabela de disponibilidade de QoS
self.hasQoS[dpid][prt]+=classlist[self.portMap[net.dstip][1]].pico
#Copia os parametros de cabecalho do pacote UDP
msg1=of.ofp_flow_mod(command=of.OFPFC_MODIFY)
msg1.match = of.ofp_match.from_packet(packet,inport)
#Altera os parametros de cabecalho para o futuro fluxo TCP
msg1.priority=65535
msg1.idle_timeout=30
msg1.hard_timeout=120
msg1.match.nw_proto=6
msg1.match.nw_tos=0
msg1.match.tp_src=SERVER_PORT
msg1.match.tp_dst=port
msg1.actions.append(of.ofp_action_enqueue(port=prt,queue_id=queue))
#Instala a regra no roteador
event.connection.send(msg1)
log.info("Fila %d aplicada ao fluxo tp_dst %d",queue,port)
##########################################################################################################
########################################### Instrucoes QoS ###############################################
##########################################################################################################
elif self.arp_for_unknowns:
# We don't know this destination.
# First, we track this buffer so that we can try to resend it later
# if we learn the destination, second we ARP for the destination,
# which should ultimately result in it responding and us learning
# where it is
# Add to tracked buffers
if (dpid,dstaddr) not in self.lost_buffers:
self.lost_buffers[(dpid,dstaddr)] = []
bucket = self.lost_buffers[(dpid,dstaddr)]
entry = (time.time() + MAX_BUFFER_TIME,event.ofp.buffer_id,inport)
bucket.append(entry)
while len(bucket) > MAX_BUFFERED_PER_IP: del bucket[0]
# Expire things from our outstanding ARP list...
self.outstanding_arps = {k:v for k,v in
self.outstanding_arps.iteritems() if v > time.time()}
# Check if we've already ARPed recently
if (dpid,dstaddr) in self.outstanding_arps:
# Oop, we've already done this one recently.
return
# And ARP...
self.outstanding_arps[(dpid,dstaddr)] = time.time() + 4
r = arp()
r.hwtype = r.HW_TYPE_ETHERNET
r.prototype = r.PROTO_TYPE_IP
r.hwlen = 6
r.protolen = r.protolen
r.opcode = r.REQUEST
r.hwdst = ETHER_BROADCAST
r.protodst = dstaddr
r.hwsrc = packet.src
r.protosrc = packet.next.srcip
e = ethernet(type=ethernet.ARP_TYPE, src=packet.src,
dst=ETHER_BROADCAST)
e.set_payload(r)
log.debug("%i %i ARPing for %s on behalf of %s" % (dpid, inport,
str(r.protodst), str(r.protosrc)))
msg = of.ofp_packet_out()
msg.data = e.pack()
msg.actions.append(of.ofp_action_output(port = of.OFPP_FLOOD))
msg.in_port = inport
event.connection.send(msg)
elif isinstance(packet.next, arp):
a = packet.next
log.debug("%i %i ARP %s %s => %s", dpid, inport,
{arp.REQUEST:"request",arp.REPLY:"reply"}.get(a.opcode,
'op:%i' % (a.opcode,)), str(a.protosrc), str(a.protodst))
if a.prototype == arp.PROTO_TYPE_IP:
if a.hwtype == arp.HW_TYPE_ETHERNET:
if a.protosrc != 0:
# Learn or update port/MAC info
if a.protosrc in self.arpTable[dpid]:
if self.arpTable[dpid][a.protosrc] != (inport, packet.src):
log.info("%i %i RE-learned %s", dpid,inport,str(a.protosrc))
else:
log.debug("%i %i learned %s", dpid,inport,str(a.protosrc))
self.arpTable[dpid][a.protosrc] = Entry(inport, packet.src)
# Send any waiting packets...
self._send_lost_buffers(dpid, a.protosrc, packet.src, inport)
if a.opcode == arp.REQUEST:
# Maybe we can answer
if a.protodst in self.arpTable[dpid]:
# We have an answer...
if not self.arpTable[dpid][a.protodst].isExpired():
# .. and it's relatively current, so we'll reply ourselves
r = arp()
r.hwtype = a.hwtype
r.prototype = a.prototype
r.hwlen = a.hwlen
r.protolen = a.protolen
r.opcode = arp.REPLY
r.hwdst = a.hwsrc
r.protodst = a.protosrc
r.protosrc = a.protodst
r.hwsrc = self.arpTable[dpid][a.protodst].mac
e = ethernet(type=packet.type, src=dpid_to_mac(dpid),
dst=a.hwsrc)
e.set_payload(r)
log.debug("%i %i answering ARP for %s" % (dpid, inport,
str(r.protosrc)))
msg = of.ofp_packet_out()
msg.data = e.pack()
msg.actions.append(of.ofp_action_output(port =
of.OFPP_IN_PORT))
msg.in_port = inport
event.connection.send(msg)
return
# Didn't know how to answer or otherwise handle this ARP, so just flood it
log.debug("%i %i flooding ARP %s %s => %s" % (dpid, inport,
{arp.REQUEST:"request",arp.REPLY:"reply"}.get(a.opcode,
'op:%i' % (a.opcode,)), str(a.protosrc), str(a.protodst)))
msg = of.ofp_packet_out(in_port = inport, data = event.ofp,
action = of.ofp_action_output(port = of.OFPP_FLOOD))
event.connection.send(msg)
def launch (fakeways="", arp_for_unknowns=None):
fakeways = fakeways.replace(","," ").split()
fakeways = [IPAddr(x) for x in fakeways]
if arp_for_unknowns is None:
arp_for_unknowns = len(fakeways) > 0
else:
arp_for_unknowns = str_to_bool(arp_for_unknowns)
core.registerNew(l3_switch, fakeways, arp_for_unknowns)