This repository has been archived by the owner on May 22, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
main.py
281 lines (247 loc) · 10.6 KB
/
main.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
"""Main module of amlight/mef_eline Kytos Network Application.
NApp to provision circuits from user request
"""
import json
import hashlib
import requests
from kytos.core import KytosNApp, log, rest
from kytos.core.helpers import listen_to
from flask import request, abort
from napps.amlight.mef_eline import settings
from napps.amlight.mef_eline.models import NewCircuit, Endpoint, Circuit
from napps.amlight.mef_eline.models import Path, Tag
from napps.amlight.mef_eline.flowmanager import FlowManager
from sortedcontainers import SortedDict
from .models import Endpoint
class Main(KytosNApp):
"""Main class of amlight/mef_eline_old NApp.
This class is the entry point for this napp.
"""
def setup(self):
"""Replace the '__init__' method for the KytosNApp subclass.
The setup method is automatically called by the controller when your
application is loaded.
So, if you have any setup routine, insert it here.
"""
self._scheduled_circuits = []
self._installed_circuits = {'ids': SortedDict(), 'ports': SortedDict()}
self.execute_as_loop(settings.INSTALL_INTERVAL)
def execute(self):
"""This method is executed right after the setup method execution.
You can also use this method in loop mode if you add to the above setup
method a line like the following example:
self.execute_as_loop(30) # 30-second interval.
"""
self._install_scheduled_circuit()
def shutdown(self):
"""This method is executed when your napp is unloaded.
If you have some cleanup procedure, insert it here.
"""
pass
def add_circuit(self, circuit):
"""
Add a circuit to the dictionaries of installed circuits
:param circuit: an instance of Circuit
"""
self._installed_circuits['ids'][circuit._id] = circuit
for endpoint in circuit._path._endpoints:
ep = '%s:%s' % (endpoint._dpid, endpoint._port)
try:
if circuit._id not in self._installed_circuits['ports'][ep]:
self._installed_circuits['ports'][ep].append(circuit._id)
except KeyError:
self._installed_circuits['ports'][ep] = [circuit._id]
@rest('/circuit', methods=['POST'])
def create_circuit(self):
"""
Receive a user request to create a new circuit, find a path for
the circuit, install the necessary flows and stores the
information about it.
:return:
"""
data = request.get_json()
if NewCircuit.validate(data):
uni_a = data['uni_a']
uni_z = data['uni_z']
url = settings.PATHFINDER_URL.format(dpid_a=uni_a['dpid'],
port_a=uni_a['port'],
dpid_z=uni_z['dpid'],
port_z=uni_z['port'])
r = requests.get(url)
if r.status_code // 100 != 2:
log.error('Pathfinder returned error code %s.' % r.status_code)
return json.dumps(False)
paths = r.json()['paths']
if len(paths) < 1:
log.error('Pathfinder returned no path.')
return json.dumps(False)
path = paths[0]['hops']
endpoints = []
m = hashlib.md5()
m.update(uni_a['dpid'].encode('utf-8'))
m.update(uni_a['port'].encode('utf-8'))
m.update(uni_z['dpid'].encode('utf-8'))
m.update(uni_z['port'].encode('utf-8'))
for endpoint in path:
dpid = endpoint[:23]
if len(endpoint) > 23:
port = endpoint[24:]
try:
if dpid == uni_a['dpid'] and port == uni_a['port']:
tag = Tag(uni_a['tag']['type'], uni_a['tag']['value'])
elif dpid == uni_z['dpid'] and port == uni_z['port']:
tag = Tag(uni_a['tag']['type'], uni_a['tag']['value'])
else:
tag = None
except KeyError:
tag = None
endpoints.append(Endpoint(dpid, port, tag))
circuit = Circuit(m.hexdigest(), data['name'], Path(endpoints))
self._scheduled_circuits.append(circuit)
else:
abort(400)
return json.dumps(circuit._id), 200, \
{'Content-Type': 'application/json; charset=utf-8'}
@rest('/circuit/<circuit_id>', methods=['GET', 'POST', 'DELETE'])
def circuit_operation(self, circuit_id):
"""
Operations on a single circuit: Retrieve, update and delete.
:param circuit_id:
:return:
"""
if request.method == 'GET':
try:
circuit = self._installed_circuits['ids'].get(circuit_id)
return (json.dumps(circuit.to_dict()), 200,
{'Content-Type' : 'application/json; charset=utf-8'})
except KeyError:
abort(404)
elif request.method == 'POST':
try:
circuit = self._installed_circuits['ids'].get(circuit_id)
data = request.get_json()
if Circuit.validate(data):
circuit._name = data['name']
endpoints = []
try:
for endpoint in data['path']['endpoints']:
dpid = endpoint['dpid']
port = endpoint['port']
endpoints.append(Endpoint(dpid, port))
except KeyError:
pass
circuit._path = Path(endpoints)
# Remove old circuit path from ports dict
for circuits in self._installed_circuits['ports'].values():
try:
circuits.remove(circuit_id)
except ValueError:
pass
self.add_circuit(circuit)
else:
abort(400)
return json.dumps(circuit_id), 200, \
{'Content-Type': 'application/json; charset=utf-8'}
except KeyError:
abort(404)
elif request.method == 'DELETE':
circuit = self._installed_circuits['ids'].get(circuit_id)
if circuit:
# TODO: remove flows from switches
del self._installed_circuits['ids'][circuit_id]
for circuits in self._installed_circuits['ports'].values():
try:
circuits.remove(circuit_id)
except ValueError:
pass
return json.dumps("Ok"), 200, \
{'Content-Type': 'application/json; charset=utf-8'}
else:
abort(404)
@rest('/circuits', methods=['GET'])
def get_circuits(self):
"""
Get all installed circuits
:return:
"""
circuits = []
for circuit in self._installed_circuits['ids'].values():
circuits.append(circuit.to_dict())
return json.dumps(circuits), 200, \
{'Content-Type': 'application/json; charset=utf-8'}
@rest('/circuits/byLink/<link_id>')
def circuits_by_link(self, link_id):
pass
@rest('/circuits/byUNI/<dpid>/<port>')
def circuits_by_uni(self, dpid, port):
"""
Get all circuits using given UNI
:param dpid:
:param port:
:return:
"""
port = '%s:%s' % (dpid, port)
circuits = []
try:
for circuit_id in self._installed_circuits['ports'][port]:
circuit = self._installed_circuits['ids'].get(circuit_id)
circuits.append(circuit.to_dict())
except KeyError:
abort(404)
return json.dumps(circuits), 200, \
{'Content-Type': 'application/json; charset=utf-8'}
@rest('/circuits/triggerinstall')
def triggerinstall(self):
self._install_scheduled_circuit()
return json.dumps({"response": "OK"}), 200
def _install_scheduled_circuit(self):
# Install path flows from all scheduled circuits.
# The method remove the circuit from the schedule list and try to install the flows.
# In case of error, the circuit returns for the schedule list
if self._scheduled_circuits:
log.info('Installing %d circuits.' % len(self._scheduled_circuits))
rollback_circuits = []
flow_manager = FlowManager(self.controller)
for circuit in self._scheduled_circuits:
try:
# TODO check start date to install circuit
# Install circuit flows
self._install_circuit(circuit, flow_manager)
except Exception as error:
log.error('Exception raised %s' % error)
# In case of error, save the circuit for later treatment
rollback_circuits.append(circuit)
# Register rollback circuits to scheduled circuits to try again
self._scheduled_circuits = rollback_circuits
def _install_circuit(self, circuit: Circuit, flow_manager):
"""Install the flows of a circuit path.
Only the main path will be installed. The backup path will not be used here.
Args:
circuit (Circuit): Circuit with a path specified to be installed
"""
# Save the circuit
self.add_circuit(circuit)
# Install the circuit path
flow_manager.install_circuit(circuit)
@listen_to('kytos/of_core.switch.interface.*')
def update_circuits(self, event):
log.info('Port status modified detected')
interface = event.content['interface']
port = '%s:%s' % (interface.switch.dpid, interface.port_number)
try:
for circuit_id in self._installed_circuits['ports'][port]:
circuit = self._installed_circuits['ids'][circuit_id]
if self.test_uni(circuit, interface.switch.dpid, interface.port_number):
continue
# TODO: modify path
except KeyError:
pass
@staticmethod
def test_uni(circuit, dpid, port):
uni_a = circuit._path._endpoints[0]
uni_z = circuit._path._endpoints[-1]
if (uni_a._dpid == dpid and int(uni_a._port) == int(port)) \
or (uni_z._dpid == dpid and int(uni_z._port) == int(port)):
log.info('UNI is down!')
return True
return False