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
|
from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER, DEAD_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_3
from ryu.lib import hub
from ryu.lib.packet import packet, ethernet, arp, ether_types
from ryu.topology import event
from ryu.topology.api import get_switch, get_link
import networkx as nx
class DynamicLoadBalance(app_manager.RyuApp):
OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]
def __init__(self, *args, **kwargs):
super(DynamicLoadBalance, self).__init__(*args, **kwargs)
self.net = nx.DiGraph()
self.mac_to_port = {}
self.arp_table = {}
self.datapaths = {}
self.monitor_thread = hub.spawn(self._monitor)
self.port_stats = {}
self.port_speed = {}
self.THRESHOLD = 1024 * 1024 * 1
self.DEFAULT_WEIGHT = 1
self.CONGESTED_WEIGHT = 100
@set_ev_cls(ofp_event.EventOFPStateChange, [MAIN_DISPATCHER, DEAD_DISPATCHER])
def _state_change_handler(self, ev):
datapath = ev.datapath
if ev.state == MAIN_DISPATCHER:
if datapath.id not in self.datapaths:
self.datapaths[datapath.id] = datapath
elif ev.state == DEAD_DISPATCHER:
if datapath.id in self.datapaths:
del self.datapaths[datapath.id]
@set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)
def switch_features_handler(self, ev):
datapath = ev.msg.datapath
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
match = parser.OFPMatch()
actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,
ofproto.OFPCML_NO_BUFFER)]
self.add_flow(datapath, 0, match, actions)
def add_flow(self, datapath, priority, match, actions, buffer_id=None):
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS, actions)]
if buffer_id:
mod = parser.OFPFlowMod(datapath=datapath, buffer_id=buffer_id,
priority=priority, match=match, instructions=inst)
else:
mod = parser.OFPFlowMod(datapath=datapath, priority=priority,
match=match, instructions=inst)
datapath.send_msg(mod)
def _monitor(self):
"""每隔 3 秒向所有交换机请求端口统计信息"""
while True:
for dp in self.datapaths.values():
self._request_stats(dp)
hub.sleep(3)
def _request_stats(self, datapath):
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
req = parser.OFPPortStatsRequest(datapath, 0, ofproto.OFPP_ANY)
datapath.send_msg(req)
@set_ev_cls(ofp_event.EventOFPPortStatsReply, MAIN_DISPATCHER)
def _port_stats_reply_handler(self, ev):
body = ev.msg.body
dpid = ev.msg.datapath.id
for stat in body:
port_no = stat.port_no
if port_no > 1000:
continue
key = (dpid, port_no)
tmp_bytes = stat.tx_bytes + stat.rx_bytes
if key in self.port_stats:
prev_bytes = self.port_stats[key]
speed = (tmp_bytes - prev_bytes) / 3.0
self.port_speed[key] = speed
self._adjust_link_weight(dpid, port_no, speed)
self.port_stats[key] = tmp_bytes
def _adjust_link_weight(self, dpid, port_no, speed):
"""如果流量超过阈值,增加图中对应边的权重"""
for u, v, data in self.net.edges(data=True):
if u == dpid and data['port'] == port_no:
if speed > self.THRESHOLD:
if data['weight'] == self.DEFAULT_WEIGHT:
print(f"!!! 拥塞告警 [Switch {dpid} Port {port_no}] 速率: {speed/1024:.2f} KB/s. 切换线路!")
self.net[u][v]['weight'] = self.CONGESTED_WEIGHT
self.del_flow(self.datapaths[dpid], port_no)
else:
if data['weight'] == self.CONGESTED_WEIGHT:
print(f"*** 拥塞解除 [Switch {dpid} Port {port_no}]. 恢复默认线路.")
self.net[u][v]['weight'] = self.DEFAULT_WEIGHT
self.del_flow(self.datapaths[dpid], port_no)
break
def del_flow(self, datapath, out_port):
"""删除指定输出端口的流表,迫使下一包触发 Packet-In 重新计算路径"""
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
match = parser.OFPMatch()
mod = parser.OFPFlowMod(datapath=datapath, command=ofproto.OFPFC_DELETE,
out_port=out_port, out_group=ofproto.OFPG_ANY,
priority=1, match=match)
datapath.send_msg(mod)
@set_ev_cls(event.EventSwitchEnter)
def get_topology_data(self, ev):
switch_list = get_switch(self, None)
switches = [switch.dp.id for switch in switch_list]
self.net.add_nodes_from(switches)
@set_ev_cls(event.EventLinkAdd)
def get_link_data(self, ev):
links_list = get_link(self, None)
for link in links_list:
self.net.add_edge(link.src.dpid, link.dst.dpid,
port=link.src.port_no, weight=self.DEFAULT_WEIGHT)
self.net.add_edge(link.dst.dpid, link.src.dpid,
port=link.dst.port_no, weight=self.DEFAULT_WEIGHT)
@set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
def _packet_in_handler(self, ev):
msg = ev.msg
datapath = msg.datapath
dpid = datapath.id
parser = datapath.ofproto_parser
in_port = msg.match['in_port']
pkt = packet.Packet(msg.data)
eth = pkt.get_protocols(ethernet.ethernet)[0]
if eth.ethertype == ether_types.ETH_TYPE_LLDP or eth.ethertype == ether_types.ETH_TYPE_IPV6:
return
dst = eth.dst
src = eth.src
if src not in self.net:
self.net.add_node(src)
self.net.add_edge(dpid, src, port=in_port, weight=0)
self.net.add_edge(src, dpid, weight=0)
if eth.ethertype == ether_types.ETH_TYPE_ARP:
self.handle_arp(datapath, in_port, pkt)
return
if dst in self.net:
try:
path = nx.shortest_path(self.net, src, dst, weight='weight')
if dpid not in path: return
next_hop = path[path.index(dpid) + 1]
out_port = self.net[dpid][next_hop]['port']
match = parser.OFPMatch(in_port=in_port, eth_dst=dst, eth_src=src)
actions = [parser.OFPActionOutput(out_port)]
self.add_flow(datapath, 1, match, actions, msg.buffer_id)
if msg.buffer_id == datapath.ofproto.OFP_NO_BUFFER:
out = parser.OFPPacketOut(datapath=datapath, buffer_id=msg.buffer_id,
in_port=in_port, actions=actions, data=msg.data)
datapath.send_msg(out)
except:
pass
def handle_arp(self, datapath, in_port, pkt):
"""ARP 代理逻辑:如果控制器知道 IP 对应的 MAC,直接回复,不泛洪"""
arp_pkt = pkt.get_protocol(arp.arp)
src_ip = arp_pkt.src_ip
src_mac = arp_pkt.src_mac
dst_ip = arp_pkt.dst_ip
self.arp_table[src_ip] = src_mac
if arp_pkt.opcode == arp.ARP_REQUEST:
if dst_ip in self.arp_table:
dst_mac = self.arp_table[dst_ip]
self.send_arp_reply(datapath, in_port, src_mac, src_ip, dst_mac, dst_ip)
else:
self.flood(datapath, in_port, pkt)
elif arp_pkt.opcode == arp.ARP_REPLY:
self.flood(datapath, in_port, pkt)
def send_arp_reply(self, datapath, port, src_mac, src_ip, dst_mac, dst_ip):
"""构造并发送 ARP Reply"""
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
pkt = packet.Packet()
pkt.add_protocol(ethernet.ethernet(ethertype=ether_types.ETH_TYPE_ARP,
dst=src_mac, src=dst_mac))
pkt.add_protocol(arp.arp(opcode=arp.ARP_REPLY,
src_mac=dst_mac, src_ip=dst_ip,
dst_mac=src_mac, dst_ip=src_ip))
pkt.serialize()
actions = [parser.OFPActionOutput(port)]
out = parser.OFPPacketOut(datapath=datapath, buffer_id=ofproto.OFP_NO_BUFFER,
in_port=ofproto.OFPP_CONTROLLER,
actions=actions, data=pkt.data)
datapath.send_msg(out)
def flood(self, datapath, in_port, pkt):
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
actions = [parser.OFPActionOutput(ofproto.OFPP_FLOOD)]
out = parser.OFPPacketOut(datapath=datapath, buffer_id=ofproto.OFP_NO_BUFFER,
in_port=in_port, actions=actions, data=pkt.data)
datapath.send_msg(out)
|