-
Notifications
You must be signed in to change notification settings - Fork 2
/
my_topo_add_ryu_with_neo.py
181 lines (149 loc) · 6.94 KB
/
my_topo_add_ryu_with_neo.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
################################
# @author: Qianru Zhou
# @email: [email protected]
# All rights reserved
#################################
import logging
from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_3# , ofproto_v1_2
#from ryu.app.stardogBackend import StardogBackend, EventInsertTuples
from ryu.lib import hub
from ryu.topology import event, switches
from rdflib import Graph, Namespace, Literal# , plugin
from rdflib.namespace import RDF
from neo4j.v1 import GraphDatabase, basic_auth
LOG = logging.getLogger("SemanticWeb")
class SemanticWeb(app_manager.RyuApp):
OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]
_CONTEXTS = {
'switches': switches.Switches,
# 'backend': StardogBackend
}
def __init__(self, *args, **kwargs):
super(SemanticWeb, self).__init__(*args, **kwargs)
self.ns = Namespace('http://home.eps.hw.ac.uk/~qz1/')
self.db_output = 'my_buff_switchStatus.rdf'
self.is_active = True
self.TIMEOUT_CHECK_PERIOD = 5
self.g = Graph()
self.topo = kwargs["switches"]
# init graph database
self.driver = GraphDatabase.driver("bolt://localhost", auth=basic_auth("neo4j", "neo4j"))
self.session = self.driver.session()
self.export_event = hub.Event()
self.threads.append(hub.spawn(self.export_loop))
def __del__(self):
self.dump_graphDatabase()
self.session.close()
def add_flow(self, datapath, priority, match, actions):
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
# construct flow_mod message and send it.
inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS,
actions)]
mod = parser.OFPFlowMod(datapath=datapath, priority=priority,
match=match, instructions=inst)
datapath.send_msg(mod)
@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
# install the table-miss flow entry.
match = parser.OFPMatch()
actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,
ofproto.OFPCML_NO_BUFFER)]
self.add_flow(datapath, 0, match, actions)
@set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
def _packet_in_handler(self, ev):
# self.topo.host_discovery_packet_in_handler(ev)
return
def dump_graphDatabase(self):
results = self.session.run("MATCH (n)-[c]-() RETURN n, c")
for r in results:
print r
def close(self):
self.is_active = False
self.export_event.set()
hub.joinall(self.threads)
def export_loop(self):
while self.is_active:
self.export_event.clear()
self.clearGraphDatabase()
LOG.error("event fired!")
self.g = Graph()
# try:
sws = self.get_switches()
for sw in sws:
s = 's' + str(sw.dp.id)
self.g.add( (self.ns[s], RDF.type, self.ns['Switch']) )
LOG.error("sw %s", sw.dp.id)
self.g.add( (self.ns[s], self.ns.hasName, Literal(s)) )
self.g.add( (self.ns[s], self.ns.hasID, Literal(sw.dp.id)) )
self.session.run("CREATE ("+ s +":Node {name:'"+ s +"', isSwitch:1 })")
for p in sw.ports:
pid = s + "_port" + str(p.port_no)
self.g.add( (self.ns[s], self.ns.hasPort, self.ns[pid]) )
self.g.add( (self.ns[pid], RDF.type, self.ns['Port']) )
self.g.add( (self.ns[pid], self.ns.isIn, self.ns[s]) )
self.g.add( (self.ns[pid], self.ns.hasName, Literal(p.name)) )
self.g.add( (self.ns[pid], self.ns.hasMAC, Literal(p.hw_addr)) )
self.g.add( (self.ns[pid], self.ns.port_no, Literal(p.port_no)) )
hosts = self.get_hosts()
hid_gen = 0
for h in hosts:
print "for h in hosts" + h
hid_gen += 1
swid = 's' + str(h.port.dpid)
hid = swid + "_host" + str(hid_gen)
pid = swid + "_port" + str(h.port.port_no)
self.g.add( (self.ns[hid], RDF.type, self.ns['Host']) )
self.g.add( (self.ns[swid], self.ns.hasHost, self.ns[hid]) )
self.g.add( (self.ns[hid], self.ns.connectToPort, self.ns[pid]) )
self.g.add( (self.ns[hid], self.ns.hasIPv4, Literal(h.ipv4)) )
self.g.add( (self.ns[hid], self.ns.hasMAC, Literal(h.mac)) )
self.session.run("CREATE ("+ hid +":Node {name:'"+ hid +"', isSwitch:0 })")
links = self.get_links()
for link in links:
print "for link in links" + link
sid = 's' + str(link.src.dpid)
spid = sid + "_port" + str(link.src.port_no)
did = 's' + str(link.dst.dpid)
dpid = did + "_port" + str(link.dst.port_no)
self.g.add( (self.ns[spid], self.ns.connectToPort,
self.ns[dpid]) )
self.g.add( (self.ns[dpid], self.ns.connectToPort,
self.ns[spid]) )
self.session.run(" MATCH (n1:Node {name:'"+ sid +"'}), (n2:Node {name:'"+ did +"'}) CREATE (n1)-[:CONNECT]->(n2)" )
print(link.src.dpid + " " + link.dst.dpid)
# except:
# LOG.error("Unexpected error: %s", sys.exc_info()[0])
with open(self.db_output, 'w') as f:
f.write(self.g.serialize(format = 'turtle'))
f.close()
# rep = self.send_request(EventInsertTuples(self.g))
# print("Query succeed? %s", rep.result)
# self.export_event.wait(timeout=self.TIMEOUT_CHECK_PERIOD)
def get_switches(self):
rep = self.send_request(event.EventSwitchRequest(None))
return rep.switches
def get_hosts(self):
rep = self.send_request(event.EventHostRequest(None))
print "get hosts:" + str(rep.hosts)
return rep.hosts
def get_links(self):
rep = self.send_request(event.EventLinkRequest(None))
print "get links:" + str(rep.links)
return rep.links
def findShortestPath(self, node1, node2):
path = self.session.run("MATCH (start:Node {name:'"+ node1 +"'}), (end:Node {name:'"+ node2 +"'}), p = shortestPath((start)-[:CONNECT*]-(end)) RETURN P")
for p in path:
print p["p"]
def clearLinkedDataModel(self):
with open(self.file_abs, 'w') as f:
f.write('')
def clearGraphDatabase(self):
self.session.run("MATCH (n) DETACH DELETE n")