1
|
|
|
"""Main module of kytos/topology Kytos Network Application. |
2
|
|
|
|
3
|
|
|
Manage the network topology |
4
|
|
|
""" |
5
|
|
|
# pylint: disable=wrong-import-order |
6
|
1 |
|
import pathlib |
7
|
1 |
|
import time |
8
|
1 |
|
from collections import defaultdict |
9
|
1 |
|
from contextlib import ExitStack |
10
|
1 |
|
from datetime import timezone |
11
|
1 |
|
from threading import Lock |
12
|
1 |
|
from typing import Iterable, List, Optional |
13
|
|
|
|
14
|
1 |
|
import httpx |
15
|
1 |
|
import tenacity |
16
|
1 |
|
from tenacity import (retry_if_exception_type, stop_after_attempt, |
17
|
|
|
wait_combine, wait_fixed, wait_random) |
18
|
|
|
|
19
|
1 |
|
from kytos.core import KytosEvent, KytosNApp, log, rest |
20
|
1 |
|
from kytos.core.common import EntityStatus, GenericEntity |
21
|
1 |
|
from kytos.core.exceptions import (KytosInvalidTagRanges, |
22
|
|
|
KytosLinkCreationError, KytosTagError) |
23
|
1 |
|
from kytos.core.helpers import listen_to, load_spec, now, validate_openapi |
24
|
1 |
|
from kytos.core.interface import Interface |
25
|
1 |
|
from kytos.core.link import Link |
26
|
1 |
|
from kytos.core.rest_api import (HTTPException, JSONResponse, Request, |
27
|
|
|
content_type_json_or_415, get_json_or_400) |
28
|
1 |
|
from kytos.core.retry import before_sleep |
29
|
1 |
|
from kytos.core.switch import Switch |
30
|
1 |
|
from kytos.core.tag_ranges import get_tag_ranges |
31
|
1 |
|
from napps.kytos.topology import settings |
32
|
|
|
|
33
|
1 |
|
from .controllers import TopoController |
34
|
1 |
|
from .exceptions import RestoreError |
35
|
1 |
|
from .models import Topology |
36
|
|
|
|
37
|
1 |
|
DEFAULT_LINK_UP_TIMER = 10 |
38
|
|
|
|
39
|
|
|
|
40
|
1 |
|
class Main(KytosNApp): # pylint: disable=too-many-public-methods |
41
|
|
|
"""Main class of kytos/topology NApp. |
42
|
|
|
|
43
|
|
|
This class is the entry point for this napp. |
44
|
|
|
""" |
45
|
|
|
|
46
|
1 |
|
spec = load_spec(pathlib.Path(__file__).parent / "openapi.yml") |
47
|
|
|
|
48
|
1 |
|
def setup(self): |
49
|
|
|
"""Initialize the NApp's links list.""" |
50
|
1 |
|
self.link_up_timer = getattr(settings, 'LINK_UP_TIMER', |
51
|
|
|
DEFAULT_LINK_UP_TIMER) |
52
|
|
|
|
53
|
|
|
# to keep track of potential unorded scheduled interface events |
54
|
1 |
|
self._intfs_lock = defaultdict(Lock) |
55
|
1 |
|
self._intfs_updated_at = {} |
56
|
1 |
|
self._intfs_tags_updated_at = {} |
57
|
1 |
|
self.link_up = set() |
58
|
1 |
|
self.link_status_lock = Lock() |
59
|
1 |
|
self._switch_lock = defaultdict(Lock) |
60
|
1 |
|
self.topo_controller = self.get_topo_controller() |
61
|
|
|
|
62
|
|
|
# Track when we last received a link up, that resulted in |
63
|
|
|
# activating a deactivated link. |
64
|
1 |
|
self.link_status_change = defaultdict[str, dict](dict) |
65
|
1 |
|
Link.register_status_func(f"{self.napp_id}_link_up_timer", |
66
|
|
|
self.link_status_hook_link_up_timer) |
67
|
1 |
|
Link.register_status_reason_func(f"{self.napp_id}_mismatched_reason", |
68
|
|
|
self.detect_mismatched_link) |
69
|
1 |
|
Link.register_status_func(f"{self.napp_id}_mismatched_status", |
70
|
|
|
self.link_status_mismatched) |
71
|
1 |
|
self.topo_controller.bootstrap_indexes() |
72
|
1 |
|
self.load_topology() |
73
|
|
|
|
74
|
1 |
|
@staticmethod |
75
|
1 |
|
def get_topo_controller() -> TopoController: |
76
|
|
|
"""Get TopoController.""" |
77
|
|
|
return TopoController() |
78
|
|
|
|
79
|
1 |
|
def execute(self): |
80
|
|
|
"""Execute once when the napp is running.""" |
81
|
|
|
pass |
82
|
|
|
|
83
|
1 |
|
def shutdown(self): |
84
|
|
|
"""Do nothing.""" |
85
|
|
|
log.info('NApp kytos/topology shutting down.') |
86
|
|
|
|
87
|
1 |
|
def _get_metadata(self, request: Request) -> dict: |
88
|
|
|
"""Return a JSON with metadata.""" |
89
|
1 |
|
content_type_json_or_415(request) |
90
|
1 |
|
metadata = get_json_or_400(request, self.controller.loop) |
91
|
1 |
|
if not isinstance(metadata, dict): |
92
|
1 |
|
raise HTTPException(400, "Invalid metadata value: {metadata}") |
93
|
1 |
|
return metadata |
94
|
|
|
|
95
|
1 |
|
def _get_switches_dict(self): |
96
|
|
|
"""Return a dictionary with the known switches.""" |
97
|
1 |
|
switches = {'switches': {}} |
98
|
1 |
|
for idx, switch in enumerate(self.controller.switches.copy().values()): |
99
|
1 |
|
switch_data = switch.as_dict() |
100
|
1 |
|
if not all(key in switch_data['metadata'] |
101
|
|
|
for key in ('lat', 'lng')): |
102
|
|
|
# Switches are initialized somewhere in the ocean |
103
|
|
|
switch_data['metadata']['lat'] = str(0.0) |
104
|
|
|
switch_data['metadata']['lng'] = str(-30.0+idx*10.0) |
105
|
1 |
|
switches['switches'][switch.id] = switch_data |
106
|
1 |
|
return switches |
107
|
|
|
|
108
|
1 |
|
def _get_links_dict(self): |
109
|
|
|
"""Return a dictionary with the known links.""" |
110
|
1 |
|
return {'links': {link.id: link.as_dict() for link in |
111
|
|
|
self.controller.links.copy().values()}} |
112
|
|
|
|
113
|
1 |
|
def _get_topology_dict(self): |
114
|
|
|
"""Return a dictionary with the known topology.""" |
115
|
1 |
|
return {'topology': {**self._get_switches_dict(), |
116
|
|
|
**self._get_links_dict()}} |
117
|
|
|
|
118
|
1 |
|
def _get_topology(self): |
119
|
|
|
"""Return an object representing the topology.""" |
120
|
1 |
|
return Topology(self.controller.switches.copy(), |
121
|
|
|
self.controller.links.copy()) |
122
|
|
|
|
123
|
1 |
|
def _load_link(self, link_att): |
124
|
1 |
|
endpoint_a = link_att['endpoint_a']['id'] |
125
|
1 |
|
endpoint_b = link_att['endpoint_b']['id'] |
126
|
1 |
|
link_str = link_att['id'] |
127
|
1 |
|
log.info(f"Loading link: {link_str}") |
128
|
1 |
|
interface_a = self.controller.get_interface_by_id(endpoint_a) |
129
|
1 |
|
interface_b = self.controller.get_interface_by_id(endpoint_b) |
130
|
|
|
|
131
|
1 |
|
error = f"Fail to load endpoints for link {link_str}. " |
132
|
1 |
|
if not interface_a: |
133
|
1 |
|
raise RestoreError(f"{error}, endpoint_a {endpoint_a} not found") |
134
|
1 |
|
if not interface_b: |
135
|
|
|
raise RestoreError(f"{error}, endpoint_b {endpoint_b} not found") |
136
|
|
|
|
137
|
1 |
|
_ = self.controller.get_link_or_create(interface_a, |
138
|
|
|
interface_b, |
139
|
|
|
link_att,) |
140
|
|
|
|
141
|
1 |
|
def _load_switch(self, switch_id, switch_att): |
142
|
1 |
|
log.info(f'Loading switch dpid: {switch_id}') |
143
|
1 |
|
switch = self.controller.get_switch_or_create(switch_id) |
144
|
1 |
|
if switch_att['enabled']: |
145
|
1 |
|
switch.enable() |
146
|
|
|
else: |
147
|
1 |
|
switch.disable() |
148
|
1 |
|
switch.description['manufacturer'] = switch_att.get('manufacturer', '') |
149
|
1 |
|
switch.description['hardware'] = switch_att.get('hardware', '') |
150
|
1 |
|
switch.description['software'] = switch_att.get('software') |
151
|
1 |
|
switch.description['serial'] = switch_att.get('serial', '') |
152
|
1 |
|
switch.description['data_path'] = switch_att.get('data_path', '') |
153
|
1 |
|
switch.extend_metadata(switch_att["metadata"]) |
154
|
|
|
|
155
|
1 |
|
for iface_id, iface_att in switch_att.get('interfaces', {}).items(): |
156
|
1 |
|
log.info(f'Loading interface iface_id={iface_id}') |
157
|
1 |
|
interface = switch.update_or_create_interface( |
158
|
|
|
port_no=iface_att['port_number'], |
159
|
|
|
name=iface_att['name'], |
160
|
|
|
address=iface_att.get('mac', None), |
161
|
|
|
speed=iface_att.get('speed', None)) |
162
|
1 |
|
if iface_att['enabled']: |
163
|
1 |
|
interface.enable() |
164
|
|
|
else: |
165
|
1 |
|
interface.disable() |
166
|
1 |
|
interface.lldp = iface_att['lldp'] |
167
|
1 |
|
interface.extend_metadata(iface_att["metadata"]) |
168
|
1 |
|
interface.deactivate() |
169
|
1 |
|
name = 'kytos/topology.port.created' |
170
|
1 |
|
event = KytosEvent(name=name, content={ |
171
|
|
|
'switch': switch_id, |
172
|
|
|
'port': interface.port_number, |
173
|
|
|
'port_description': { |
174
|
|
|
'alias': interface.name, |
175
|
|
|
'mac': interface.address, |
176
|
|
|
'state': interface.state |
177
|
|
|
} |
178
|
|
|
}) |
179
|
1 |
|
self.controller.buffers.app.put(event, timeout=1) |
180
|
|
|
|
181
|
1 |
|
intf_ids = [v["id"] for v in switch_att.get("interfaces", {}).values()] |
182
|
1 |
|
intf_details = self.topo_controller.get_interfaces_details(intf_ids) |
183
|
1 |
|
self.load_interfaces_tags_values(switch, intf_details) |
184
|
|
|
|
185
|
|
|
# pylint: disable=attribute-defined-outside-init |
186
|
1 |
|
def load_topology(self): |
187
|
|
|
"""Load network topology from DB.""" |
188
|
1 |
|
topology = self.topo_controller.get_topology() |
189
|
1 |
|
switches = topology["topology"]["switches"] |
190
|
1 |
|
links = topology["topology"]["links"] |
191
|
|
|
|
192
|
1 |
|
failed_switches = {} |
193
|
1 |
|
log.debug(f"_load_network_status switches={switches}") |
194
|
1 |
|
for switch_id, switch_att in switches.items(): |
195
|
1 |
|
try: |
196
|
1 |
|
self._load_switch(switch_id, switch_att) |
197
|
1 |
|
except (KeyError, AttributeError, TypeError) as err: |
198
|
1 |
|
failed_switches[switch_id] = err |
199
|
1 |
|
log.error(f'Error loading switch: {err}') |
200
|
|
|
|
201
|
1 |
|
failed_links = {} |
202
|
1 |
|
log.debug(f"_load_network_status links={links}") |
203
|
1 |
|
for link_id, link_att in links.items(): |
204
|
1 |
|
try: |
205
|
1 |
|
self._load_link(link_att) |
206
|
1 |
|
except (KeyError, AttributeError, TypeError) as err: |
207
|
1 |
|
failed_links[link_id] = err |
208
|
1 |
|
log.error(f'Error loading link {link_id}: {err}') |
209
|
|
|
|
210
|
1 |
|
next_topology = self._get_topology() |
211
|
1 |
|
name = 'kytos/topology.topology_loaded' |
212
|
1 |
|
event = KytosEvent( |
213
|
|
|
name=name, |
214
|
|
|
content={ |
215
|
|
|
'topology': next_topology, |
216
|
|
|
'failed_switches': failed_switches, |
217
|
|
|
'failed_links': failed_links |
218
|
|
|
}) |
219
|
1 |
|
self.controller.buffers.app.put(event, timeout=1) |
220
|
1 |
|
self.last_pushed_topology = next_topology |
221
|
|
|
|
222
|
1 |
|
@rest('v3/') |
223
|
1 |
|
def get_topology(self, _request: Request) -> JSONResponse: |
224
|
|
|
"""Return the latest known topology. |
225
|
|
|
|
226
|
|
|
This topology is updated when there are network events. |
227
|
|
|
""" |
228
|
1 |
|
return JSONResponse(self._get_topology_dict()) |
229
|
|
|
|
230
|
|
|
# Switch related methods |
231
|
1 |
|
@rest('v3/switches') |
232
|
1 |
|
def get_switches(self, _request: Request) -> JSONResponse: |
233
|
|
|
"""Return a json with all the switches in the topology.""" |
234
|
|
|
return JSONResponse(self._get_switches_dict()) |
235
|
|
|
|
236
|
1 |
|
@rest('v3/switches/{dpid}/enable', methods=['POST']) |
237
|
1 |
|
def enable_switch(self, request: Request) -> JSONResponse: |
238
|
|
|
"""Administratively enable a switch in the topology.""" |
239
|
1 |
|
dpid = request.path_params["dpid"] |
240
|
1 |
|
try: |
241
|
1 |
|
switch = self.controller.switches[dpid] |
242
|
1 |
|
self.topo_controller.enable_switch(dpid) |
243
|
1 |
|
switch.enable() |
244
|
1 |
|
except KeyError: |
245
|
1 |
|
raise HTTPException(404, detail="Switch not found") |
246
|
|
|
|
247
|
1 |
|
self.notify_topology_update() |
248
|
1 |
|
self.notify_switch_enabled(dpid) |
249
|
1 |
|
self.notify_switch_links_status(switch, "link enabled") |
250
|
1 |
|
return JSONResponse("Operation successful", status_code=201) |
251
|
|
|
|
252
|
1 |
|
@rest('v3/switches/{dpid}/disable', methods=['POST']) |
253
|
1 |
|
def disable_switch(self, request: Request) -> JSONResponse: |
254
|
|
|
"""Administratively disable a switch in the topology.""" |
255
|
1 |
|
dpid = request.path_params["dpid"] |
256
|
1 |
|
try: |
257
|
1 |
|
switch = self.controller.switches[dpid] |
258
|
1 |
|
link_ids = set() |
259
|
1 |
|
with ExitStack() as stack: |
260
|
1 |
|
for _, interface in switch.interfaces.copy().items(): |
261
|
1 |
|
if (interface.link and interface.link.is_enabled()): |
262
|
1 |
|
stack.enter_context(interface.link.link_lock) |
263
|
1 |
|
link_ids.add(interface.link.id) |
264
|
1 |
|
interface.link.disable() |
265
|
1 |
|
self.notify_link_enabled_state( |
266
|
|
|
interface.link, "disabled" |
267
|
|
|
) |
268
|
1 |
|
self.topo_controller.bulk_disable_links(link_ids) |
269
|
1 |
|
self.topo_controller.disable_switch(dpid) |
270
|
1 |
|
switch.disable() |
271
|
1 |
|
except KeyError: |
272
|
1 |
|
raise HTTPException(404, detail="Switch not found") |
273
|
|
|
|
274
|
1 |
|
self.notify_topology_update() |
275
|
1 |
|
self.notify_switch_disabled(dpid) |
276
|
1 |
|
self.notify_switch_links_status(switch, "link disabled") |
277
|
1 |
|
return JSONResponse("Operation successful", status_code=201) |
278
|
|
|
|
279
|
1 |
|
@rest('v3/switches/{dpid}', methods=['DELETE']) |
280
|
1 |
|
def delete_switch(self, request: Request) -> JSONResponse: |
281
|
|
|
"""Delete a switch. |
282
|
|
|
|
283
|
|
|
Requirements: |
284
|
|
|
- There should not be installed flows related to switch. |
285
|
|
|
- The switch should be disabled. |
286
|
|
|
- All tags from switch interfaces should be available. |
287
|
|
|
- The switch should not have links. |
288
|
|
|
""" |
289
|
1 |
|
dpid = request.path_params["dpid"] |
290
|
1 |
|
try: |
291
|
1 |
|
switch: Switch = self.controller.switches[dpid] |
292
|
1 |
|
with self._switch_lock[dpid]: |
293
|
1 |
|
if switch.status != EntityStatus.DISABLED: |
294
|
1 |
|
raise HTTPException( |
295
|
|
|
409, detail="Switch should be disabled." |
296
|
|
|
) |
297
|
1 |
|
for intf_id, interface in switch.interfaces.copy().items(): |
298
|
1 |
|
if not interface.all_tags_available(): |
299
|
1 |
|
detail = f"Interface {intf_id} vlans are being used."\ |
300
|
|
|
" Delete any service using vlans." |
301
|
1 |
|
raise HTTPException(409, detail=detail) |
302
|
1 |
|
with self.controller.links_lock: |
303
|
1 |
|
for link_id, link in self.controller.links.copy().items(): |
304
|
1 |
|
if (dpid in |
305
|
|
|
(link.endpoint_a.switch.dpid, |
306
|
|
|
link.endpoint_b.switch.dpid)): |
307
|
1 |
|
raise HTTPException( |
308
|
|
|
409, detail=f"Switch should not have links. " |
309
|
|
|
f"Link found {link_id}." |
310
|
|
|
) |
311
|
1 |
|
try: |
312
|
1 |
|
flows = self.get_flows_by_switch(dpid) |
313
|
|
|
except tenacity.RetryError as err: |
314
|
|
|
detail = "Error while getting flows: "\ |
315
|
|
|
f"{err.last_attempt.exception()}." |
316
|
|
|
raise HTTPException(409, detail=detail) |
317
|
1 |
|
if flows: |
318
|
|
|
raise HTTPException(409, detail="Switch has flows. Verify" |
319
|
|
|
" if a switch is used.") |
320
|
1 |
|
switch = self.controller.switches.pop(dpid) |
321
|
1 |
|
self.topo_controller.delete_switch_data(dpid) |
322
|
1 |
|
except KeyError: |
323
|
1 |
|
raise HTTPException(404, detail="Switch not found.") |
324
|
1 |
|
name = 'kytos/topology.switch.deleted' |
325
|
1 |
|
event = KytosEvent(name=name, content={'switch': switch}) |
326
|
1 |
|
self.controller.buffers.app.put(event) |
327
|
1 |
|
self.notify_topology_update() |
328
|
1 |
|
return JSONResponse("Operation successful") |
329
|
|
|
|
330
|
1 |
|
@rest('v3/switches/{dpid}/metadata') |
331
|
1 |
|
def get_switch_metadata(self, request: Request) -> JSONResponse: |
332
|
|
|
"""Get metadata from a switch.""" |
333
|
1 |
|
dpid = request.path_params["dpid"] |
334
|
1 |
|
try: |
335
|
1 |
|
metadata = self.controller.switches[dpid].metadata |
336
|
1 |
|
return JSONResponse({"metadata": metadata}) |
337
|
1 |
|
except KeyError: |
338
|
1 |
|
raise HTTPException(404, detail="Switch not found") |
339
|
|
|
|
340
|
1 |
|
@rest('v3/switches/{dpid}/metadata', methods=['POST']) |
341
|
1 |
|
def add_switch_metadata(self, request: Request) -> JSONResponse: |
342
|
|
|
"""Add metadata to a switch.""" |
343
|
1 |
|
dpid = request.path_params["dpid"] |
344
|
1 |
|
metadata = self._get_metadata(request) |
345
|
1 |
|
try: |
346
|
1 |
|
switch = self.controller.switches[dpid] |
347
|
1 |
|
except KeyError: |
348
|
1 |
|
raise HTTPException(404, detail="Switch not found") |
349
|
|
|
|
350
|
1 |
|
self.topo_controller.add_switch_metadata(dpid, metadata) |
351
|
1 |
|
switch.extend_metadata(metadata) |
352
|
1 |
|
self.notify_metadata_changes(switch, 'added') |
353
|
1 |
|
return JSONResponse("Operation successful", status_code=201) |
354
|
|
|
|
355
|
1 |
|
@rest('v3/switches/{dpid}/metadata/{key}', methods=['DELETE']) |
356
|
1 |
|
def delete_switch_metadata(self, request: Request) -> JSONResponse: |
357
|
|
|
"""Delete metadata from a switch.""" |
358
|
1 |
|
dpid = request.path_params["dpid"] |
359
|
1 |
|
key = request.path_params["key"] |
360
|
1 |
|
try: |
361
|
1 |
|
switch = self.controller.switches[dpid] |
362
|
1 |
|
except KeyError: |
363
|
1 |
|
raise HTTPException(404, detail="Switch not found") |
364
|
|
|
|
365
|
1 |
|
try: |
366
|
1 |
|
_ = switch.metadata[key] |
367
|
1 |
|
except KeyError: |
368
|
1 |
|
raise HTTPException(404, "Metadata not found") |
369
|
|
|
|
370
|
1 |
|
self.topo_controller.delete_switch_metadata_key(dpid, key) |
371
|
1 |
|
switch.remove_metadata(key) |
372
|
1 |
|
self.notify_metadata_changes(switch, 'removed') |
373
|
1 |
|
return JSONResponse("Operation successful") |
374
|
|
|
|
375
|
|
|
# Interface related methods |
376
|
1 |
|
@rest('v3/interfaces') |
377
|
1 |
|
def get_interfaces(self, _request: Request) -> JSONResponse: |
378
|
|
|
"""Return a json with all the interfaces in the topology.""" |
379
|
1 |
|
interfaces = {} |
380
|
1 |
|
switches = self._get_switches_dict() |
381
|
1 |
|
for switch in switches['switches'].values(): |
382
|
1 |
|
for interface_id, interface in switch['interfaces'].items(): |
383
|
1 |
|
interfaces[interface_id] = interface |
384
|
|
|
|
385
|
1 |
|
return JSONResponse({'interfaces': interfaces}) |
386
|
|
|
|
387
|
1 |
|
@rest('v3/interfaces/switch/{dpid}/enable', methods=['POST']) |
388
|
1 |
|
@rest('v3/interfaces/{interface_enable_id}/enable', methods=['POST']) |
389
|
1 |
|
def enable_interface(self, request: Request) -> JSONResponse: |
390
|
|
|
"""Administratively enable interfaces in the topology.""" |
391
|
1 |
|
interface_enable_id = request.path_params.get("interface_enable_id") |
392
|
1 |
|
dpid = request.path_params.get("dpid") |
393
|
1 |
|
if dpid is None: |
394
|
1 |
|
dpid = ":".join(interface_enable_id.split(":")[:-1]) |
395
|
1 |
|
try: |
396
|
1 |
|
switch = self.controller.switches[dpid] |
397
|
1 |
|
if not switch.is_enabled(): |
398
|
1 |
|
raise HTTPException(409, detail="Enable Switch first") |
399
|
1 |
|
except KeyError: |
400
|
1 |
|
raise HTTPException(404, detail="Switch not found") |
401
|
|
|
|
402
|
1 |
|
if interface_enable_id: |
403
|
1 |
|
interface_number = int(interface_enable_id.split(":")[-1]) |
404
|
|
|
|
405
|
1 |
|
try: |
406
|
1 |
|
interface = switch.interfaces[interface_number] |
407
|
1 |
|
self.topo_controller.enable_interface(interface.id) |
408
|
1 |
|
interface.enable() |
409
|
1 |
|
if interface.link: |
410
|
1 |
|
with interface.link.link_lock: |
411
|
1 |
|
self._notify_interface_link_status( |
412
|
|
|
[interface], "link enabled" |
413
|
|
|
) |
414
|
1 |
|
except KeyError: |
415
|
1 |
|
msg = f"Switch {dpid} interface {interface_number} not found" |
416
|
1 |
|
raise HTTPException(404, detail=msg) |
417
|
|
|
else: |
418
|
1 |
|
for interface in switch.interfaces.copy().values(): |
419
|
1 |
|
interface.enable() |
420
|
1 |
|
if interface.link: |
421
|
1 |
|
with interface.link.link_lock: |
422
|
1 |
|
self._notify_interface_link_status( |
423
|
|
|
[interface], "link enabled" |
424
|
|
|
) |
425
|
1 |
|
self.topo_controller.upsert_switch(switch.id, switch.as_dict()) |
426
|
1 |
|
self.notify_topology_update() |
427
|
1 |
|
return JSONResponse("Operation successful") |
428
|
|
|
|
429
|
1 |
|
@rest('v3/interfaces/switch/{dpid}/disable', methods=['POST']) |
430
|
1 |
|
@rest('v3/interfaces/{interface_disable_id}/disable', methods=['POST']) |
431
|
1 |
|
def disable_interface(self, request: Request) -> JSONResponse: |
432
|
|
|
"""Administratively disable interfaces in the topology.""" |
433
|
1 |
|
interface_disable_id = request.path_params.get("interface_disable_id") |
434
|
1 |
|
dpid = request.path_params.get("dpid") |
435
|
1 |
|
if dpid is None: |
436
|
1 |
|
dpid = ":".join(interface_disable_id.split(":")[:-1]) |
437
|
1 |
|
try: |
438
|
1 |
|
switch = self.controller.switches[dpid] |
439
|
1 |
|
except KeyError: |
440
|
1 |
|
raise HTTPException(404, detail="Switch not found") |
441
|
|
|
|
442
|
1 |
|
interfaces: list[Interface] = [] |
443
|
1 |
|
if interface_disable_id: |
444
|
1 |
|
try: |
445
|
1 |
|
interface_number = int(interface_disable_id.split(":")[-1]) |
446
|
1 |
|
interfaces = [switch.interfaces[interface_number]] |
447
|
1 |
|
self.topo_controller.disable_interface(interfaces[0].id) |
448
|
1 |
|
except KeyError: |
449
|
1 |
|
msg = f"Switch {dpid} interface {interface_number} not found" |
450
|
1 |
|
raise HTTPException(404, detail=msg) |
451
|
|
|
else: |
452
|
1 |
|
interfaces = switch.interfaces.copy().values() |
453
|
|
|
|
454
|
1 |
|
link_ids: set[Link] = set() |
455
|
1 |
|
with ExitStack() as stack: |
456
|
1 |
|
for interface in interfaces: |
457
|
1 |
|
if interface.link and interface.link.is_enabled(): |
458
|
1 |
|
stack.enter_context(interface.link.link_lock) |
459
|
1 |
|
link_ids.add(interface.link.id) |
460
|
1 |
|
interface.link.disable() |
461
|
1 |
|
self.notify_link_enabled_state(interface.link, "disabled") |
462
|
1 |
|
interface.disable() |
463
|
1 |
|
self._notify_interface_link_status(interfaces, "link disabled") |
464
|
1 |
|
self.topo_controller.bulk_disable_links(link_ids) |
465
|
|
|
|
466
|
1 |
|
if not interface_disable_id: |
467
|
1 |
|
self.topo_controller.upsert_switch(switch.id, switch.as_dict()) |
468
|
|
|
|
469
|
1 |
|
self.notify_topology_update() |
470
|
1 |
|
return JSONResponse("Operation successful") |
471
|
|
|
|
472
|
1 |
|
@rest('v3/interfaces/{interface_id}/metadata') |
473
|
1 |
|
def get_interface_metadata(self, request: Request) -> JSONResponse: |
474
|
|
|
"""Get metadata from an interface.""" |
475
|
1 |
|
interface_id = request.path_params["interface_id"] |
476
|
1 |
|
switch_id = ":".join(interface_id.split(":")[:-1]) |
477
|
1 |
|
interface_number = int(interface_id.split(":")[-1]) |
478
|
1 |
|
try: |
479
|
1 |
|
switch = self.controller.switches[switch_id] |
480
|
1 |
|
except KeyError: |
481
|
1 |
|
raise HTTPException(404, detail="Switch not found") |
482
|
|
|
|
483
|
1 |
|
try: |
484
|
1 |
|
interface = switch.interfaces[interface_number] |
485
|
1 |
|
except KeyError: |
486
|
1 |
|
raise HTTPException(404, detail="Interface not found") |
487
|
|
|
|
488
|
1 |
|
return JSONResponse({"metadata": interface.metadata}) |
489
|
|
|
|
490
|
1 |
|
@rest('v3/interfaces/{interface_id}/metadata', methods=['POST']) |
491
|
1 |
|
def add_interface_metadata(self, request: Request) -> JSONResponse: |
492
|
|
|
"""Add metadata to an interface.""" |
493
|
1 |
|
interface_id = request.path_params["interface_id"] |
494
|
1 |
|
metadata = self._get_metadata(request) |
495
|
1 |
|
switch_id = ":".join(interface_id.split(":")[:-1]) |
496
|
1 |
|
interface_number = int(interface_id.split(":")[-1]) |
497
|
1 |
|
try: |
498
|
1 |
|
switch = self.controller.switches[switch_id] |
499
|
1 |
|
except KeyError: |
500
|
1 |
|
raise HTTPException(404, detail="Switch not found") |
501
|
|
|
|
502
|
1 |
|
try: |
503
|
1 |
|
interface = switch.interfaces[interface_number] |
504
|
1 |
|
self.topo_controller.add_interface_metadata(interface.id, metadata) |
505
|
1 |
|
except KeyError: |
506
|
1 |
|
raise HTTPException(404, detail="Interface not found") |
507
|
|
|
|
508
|
1 |
|
interface.extend_metadata(metadata) |
509
|
1 |
|
self.notify_metadata_changes(interface, 'added') |
510
|
1 |
|
return JSONResponse("Operation successful", status_code=201) |
511
|
|
|
|
512
|
1 |
|
@rest('v3/interfaces/{interface_id}/metadata/{key}', methods=['DELETE']) |
513
|
1 |
|
def delete_interface_metadata(self, request: Request) -> JSONResponse: |
514
|
|
|
"""Delete metadata from an interface.""" |
515
|
1 |
|
interface_id = request.path_params["interface_id"] |
516
|
1 |
|
key = request.path_params["key"] |
517
|
1 |
|
switch_id = ":".join(interface_id.split(":")[:-1]) |
518
|
1 |
|
try: |
519
|
1 |
|
interface_number = int(interface_id.split(":")[-1]) |
520
|
|
|
except ValueError: |
521
|
|
|
detail = f"Invalid interface_id {interface_id}" |
522
|
|
|
raise HTTPException(400, detail=detail) |
523
|
|
|
|
524
|
1 |
|
try: |
525
|
1 |
|
switch = self.controller.switches[switch_id] |
526
|
1 |
|
except KeyError: |
527
|
1 |
|
raise HTTPException(404, detail="Switch not found") |
528
|
|
|
|
529
|
1 |
|
try: |
530
|
1 |
|
interface = switch.interfaces[interface_number] |
531
|
1 |
|
except KeyError: |
532
|
1 |
|
raise HTTPException(404, detail="Interface not found") |
533
|
|
|
|
534
|
1 |
|
try: |
535
|
1 |
|
_ = interface.metadata[key] |
536
|
1 |
|
except KeyError: |
537
|
1 |
|
raise HTTPException(404, detail="Metadata not found") |
538
|
|
|
|
539
|
1 |
|
self.topo_controller.delete_interface_metadata_key(interface.id, key) |
540
|
1 |
|
interface.remove_metadata(key) |
541
|
1 |
|
self.notify_metadata_changes(interface, 'removed') |
542
|
1 |
|
return JSONResponse("Operation successful") |
543
|
|
|
|
544
|
1 |
|
@rest('v3/interfaces/{interface_id}/tag_ranges', methods=['POST']) |
545
|
1 |
|
@validate_openapi(spec) |
546
|
1 |
|
def set_tag_range(self, request: Request) -> JSONResponse: |
547
|
|
|
"""Set tag range""" |
548
|
1 |
|
content_type_json_or_415(request) |
549
|
1 |
|
content = get_json_or_400(request, self.controller.loop) |
550
|
1 |
|
tag_type = content.get("tag_type") |
551
|
1 |
|
try: |
552
|
1 |
|
ranges = get_tag_ranges(content["tag_ranges"]) |
553
|
|
|
except KytosInvalidTagRanges as err: |
554
|
|
|
raise HTTPException(400, detail=str(err)) |
555
|
1 |
|
interface_id = request.path_params["interface_id"] |
556
|
1 |
|
interface = self.controller.get_interface_by_id(interface_id) |
557
|
1 |
|
if not interface: |
558
|
1 |
|
raise HTTPException(404, detail="Interface not found") |
559
|
1 |
|
try: |
560
|
1 |
|
interface.set_tag_ranges(ranges, tag_type) |
561
|
1 |
|
self.handle_on_interface_tags(interface) |
562
|
1 |
|
except KytosTagError as err: |
563
|
1 |
|
raise HTTPException(400, detail=str(err)) |
564
|
1 |
|
return JSONResponse("Operation Successful", status_code=200) |
565
|
|
|
|
566
|
1 |
|
@rest('v3/interfaces/{interface_id}/tag_ranges', methods=['DELETE']) |
567
|
1 |
|
@validate_openapi(spec) |
568
|
1 |
|
def delete_tag_range(self, request: Request) -> JSONResponse: |
569
|
|
|
"""Set tag_range from tag_type to default value [1, 4095]""" |
570
|
1 |
|
interface_id = request.path_params["interface_id"] |
571
|
1 |
|
params = request.query_params |
572
|
1 |
|
tag_type = params.get("tag_type", 'vlan') |
573
|
1 |
|
interface = self.controller.get_interface_by_id(interface_id) |
574
|
1 |
|
if not interface: |
575
|
1 |
|
raise HTTPException(404, detail="Interface not found") |
576
|
1 |
|
try: |
577
|
1 |
|
interface.remove_tag_ranges(tag_type) |
578
|
1 |
|
self.handle_on_interface_tags(interface) |
579
|
1 |
|
except KytosTagError as err: |
580
|
1 |
|
raise HTTPException(400, detail=str(err)) |
581
|
1 |
|
return JSONResponse("Operation Successful", status_code=200) |
582
|
|
|
|
583
|
1 |
|
@rest('v3/interfaces/{interface_id}/special_tags', methods=['POST']) |
584
|
1 |
|
@validate_openapi(spec) |
585
|
1 |
|
def set_special_tags(self, request: Request) -> JSONResponse: |
586
|
|
|
"""Set special_tags""" |
587
|
1 |
|
content_type_json_or_415(request) |
588
|
1 |
|
content = get_json_or_400(request, self.controller.loop) |
589
|
1 |
|
tag_type = content.get("tag_type") |
590
|
1 |
|
special_tags = content["special_tags"] |
591
|
1 |
|
interface_id = request.path_params["interface_id"] |
592
|
1 |
|
interface = self.controller.get_interface_by_id(interface_id) |
593
|
1 |
|
if not interface: |
594
|
1 |
|
raise HTTPException(404, detail="Interface not found") |
595
|
1 |
|
try: |
596
|
1 |
|
interface.set_special_tags(tag_type, special_tags) |
597
|
1 |
|
self.handle_on_interface_tags(interface) |
598
|
1 |
|
except KytosTagError as err: |
599
|
1 |
|
raise HTTPException(400, detail=str(err)) |
600
|
1 |
|
return JSONResponse("Operation Successful", status_code=200) |
601
|
|
|
|
602
|
1 |
|
@rest('v3/interfaces/tag_ranges', methods=['GET']) |
603
|
1 |
|
@validate_openapi(spec) |
604
|
1 |
|
def get_all_tag_ranges(self, _: Request) -> JSONResponse: |
605
|
|
|
"""Get all tag_ranges, available_tags, special_tags |
606
|
|
|
and special_available_tags from interfaces""" |
607
|
1 |
|
result = {} |
608
|
1 |
|
for switch in self.controller.switches.copy().values(): |
609
|
1 |
|
for interface in switch.interfaces.copy().values(): |
610
|
1 |
|
result[interface.id] = { |
611
|
|
|
"available_tags": interface.available_tags, |
612
|
|
|
"tag_ranges": interface.tag_ranges, |
613
|
|
|
"special_tags": interface.special_tags, |
614
|
|
|
"special_available_tags": interface.special_available_tags |
615
|
|
|
} |
616
|
1 |
|
return JSONResponse(result, status_code=200) |
617
|
|
|
|
618
|
1 |
|
@rest('v3/interfaces/{interface_id}/tag_ranges', methods=['GET']) |
619
|
1 |
|
@validate_openapi(spec) |
620
|
1 |
|
def get_tag_ranges_by_intf(self, request: Request) -> JSONResponse: |
621
|
|
|
"""Get tag_ranges, available_tags, special_tags |
622
|
|
|
and special_available_tags from an interface""" |
623
|
1 |
|
interface_id = request.path_params["interface_id"] |
624
|
1 |
|
interface = self.controller.get_interface_by_id(interface_id) |
625
|
1 |
|
if not interface: |
626
|
1 |
|
raise HTTPException(404, detail="Interface not found") |
627
|
1 |
|
result = { |
628
|
|
|
interface_id: { |
629
|
|
|
"available_tags": interface.available_tags, |
630
|
|
|
"tag_ranges": interface.tag_ranges, |
631
|
|
|
"special_tags": interface.special_tags, |
632
|
|
|
"special_available_tags": interface.special_available_tags |
633
|
|
|
} |
634
|
|
|
} |
635
|
1 |
|
return JSONResponse(result, status_code=200) |
636
|
|
|
|
637
|
|
|
# Link related methods |
638
|
1 |
|
@rest('v3/links') |
639
|
1 |
|
def get_links(self, _request: Request) -> JSONResponse: |
640
|
|
|
"""Return a json with all the links in the topology. |
641
|
|
|
|
642
|
|
|
Links are connections between interfaces. |
643
|
|
|
""" |
644
|
|
|
return JSONResponse(self._get_links_dict()) |
645
|
|
|
|
646
|
1 |
|
@rest('v3/links/{link_id}/enable', methods=['POST']) |
647
|
1 |
|
def enable_link(self, request: Request) -> JSONResponse: |
648
|
|
|
"""Administratively enable a link in the topology.""" |
649
|
1 |
|
link_id = request.path_params["link_id"] |
650
|
1 |
|
link = self.controller.get_link(link_id) |
651
|
1 |
|
if not link: |
652
|
1 |
|
raise HTTPException(404, detail="Link not found") |
653
|
|
|
|
654
|
1 |
|
with link.link_lock: |
655
|
1 |
|
if not link.endpoint_a.is_enabled(): |
656
|
1 |
|
detail = f"{link.endpoint_a.id} needs enabling." |
657
|
1 |
|
raise HTTPException(409, detail=detail) |
658
|
1 |
|
if not link.endpoint_b.is_enabled(): |
659
|
1 |
|
detail = f"{link.endpoint_b.id} needs enabling." |
660
|
1 |
|
raise HTTPException(409, detail=detail) |
661
|
1 |
|
if not link.is_enabled(): |
662
|
1 |
|
self.topo_controller.enable_link(link.id) |
663
|
1 |
|
link.enable() |
664
|
1 |
|
self.notify_link_enabled_state(link, "enabled") |
665
|
1 |
|
self.notify_link_status_change(link, reason='link enabled') |
666
|
1 |
|
self.notify_topology_update() |
667
|
1 |
|
return JSONResponse("Operation successful", status_code=201) |
668
|
|
|
|
669
|
1 |
|
@rest('v3/links/{link_id}/disable', methods=['POST']) |
670
|
1 |
|
def disable_link(self, request: Request) -> JSONResponse: |
671
|
|
|
"""Administratively disable a link in the topology.""" |
672
|
1 |
|
link_id = request.path_params["link_id"] |
673
|
1 |
|
link = self.controller.get_link(link_id) |
674
|
1 |
|
if not link: |
675
|
1 |
|
raise HTTPException(404, detail="Link not found") |
676
|
|
|
|
677
|
1 |
|
with link.link_lock: |
678
|
1 |
|
if link.is_enabled(): |
679
|
1 |
|
self.topo_controller.disable_link(link.id) |
680
|
1 |
|
link.disable() |
681
|
1 |
|
self.notify_link_enabled_state(link, "disabled") |
682
|
1 |
|
self.notify_link_status_change(link, reason='link disabled') |
683
|
1 |
|
self.notify_topology_update() |
684
|
1 |
|
return JSONResponse("Operation successful", status_code=201) |
685
|
|
|
|
686
|
1 |
|
def notify_link_enabled_state(self, link: Link, action: str): |
687
|
|
|
"""Send a KytosEvent whether a link status (enabled/disabled) |
688
|
|
|
has changed its status.""" |
689
|
1 |
|
name = f'kytos/topology.link.{action}' |
690
|
1 |
|
content = {'link': link} |
691
|
1 |
|
event = KytosEvent(name=name, content=content) |
692
|
1 |
|
self.controller.buffers.app.put(event) |
693
|
|
|
|
694
|
1 |
|
@rest('v3/links/{link_id}/metadata') |
695
|
1 |
|
def get_link_metadata(self, request: Request) -> JSONResponse: |
696
|
|
|
"""Get metadata from a link.""" |
697
|
1 |
|
link_id = request.path_params["link_id"] |
698
|
1 |
|
link = self.controller.get_link(link_id) |
699
|
1 |
|
try: |
700
|
1 |
|
return JSONResponse({"metadata": link.metadata}) |
701
|
1 |
|
except AttributeError: |
702
|
1 |
|
raise HTTPException(404, detail="Link not found") |
703
|
|
|
|
704
|
1 |
|
@rest('v3/links/{link_id}/metadata', methods=['POST']) |
705
|
1 |
|
def add_link_metadata(self, request: Request) -> JSONResponse: |
706
|
|
|
"""Add metadata to a link.""" |
707
|
1 |
|
link_id = request.path_params["link_id"] |
708
|
1 |
|
metadata = self._get_metadata(request) |
709
|
1 |
|
link = self.controller.get_link(link_id) |
710
|
1 |
|
if not link: |
711
|
1 |
|
raise HTTPException(404, detail="Link not found") |
712
|
|
|
|
713
|
1 |
|
with link.link_lock: |
714
|
1 |
|
self.topo_controller.add_link_metadata(link_id, metadata) |
715
|
1 |
|
link.extend_metadata(metadata) |
716
|
1 |
|
self.notify_metadata_changes(link, 'added') |
717
|
1 |
|
self.notify_topology_update() |
718
|
1 |
|
return JSONResponse("Operation successful", status_code=201) |
719
|
|
|
|
720
|
1 |
|
@rest('v3/links/{link_id}/metadata/{key}', methods=['DELETE']) |
721
|
1 |
|
def delete_link_metadata(self, request: Request) -> JSONResponse: |
722
|
|
|
"""Delete metadata from a link.""" |
723
|
1 |
|
link_id = request.path_params["link_id"] |
724
|
1 |
|
key = request.path_params["key"] |
725
|
1 |
|
link = self.controller.get_link(link_id) |
726
|
1 |
|
if not link: |
727
|
1 |
|
raise HTTPException(404, detail="Link not found") |
728
|
|
|
|
729
|
1 |
|
with link.link_lock: |
730
|
1 |
|
try: |
731
|
1 |
|
_ = link.metadata[key] |
732
|
1 |
|
except KeyError: |
733
|
1 |
|
raise HTTPException(404, detail="Metadata not found") |
734
|
1 |
|
self.topo_controller.delete_link_metadata_key(link.id, key) |
735
|
1 |
|
link.remove_metadata(key) |
736
|
1 |
|
self.notify_metadata_changes(link, 'removed') |
737
|
1 |
|
self.notify_topology_update() |
738
|
1 |
|
return JSONResponse("Operation successful") |
739
|
|
|
|
740
|
1 |
|
@rest('v3/links/{link_id}', methods=['DELETE']) |
741
|
1 |
|
def delete_link(self, request: Request) -> JSONResponse: |
742
|
|
|
"""Delete a disabled link from topology. |
743
|
|
|
It won't work for link with other statuses. |
744
|
|
|
""" |
745
|
1 |
|
link_id = request.path_params["link_id"] |
746
|
1 |
|
link = self.controller.get_link(link_id) |
747
|
1 |
|
if not link: |
748
|
1 |
|
raise HTTPException(404, detail="Link not found.") |
749
|
1 |
|
with self.controller.links_lock: |
750
|
1 |
|
with link.link_lock: |
751
|
1 |
|
if link.status != EntityStatus.DISABLED: |
752
|
1 |
|
raise HTTPException(409, detail="Link is not disabled.") |
753
|
|
|
|
754
|
1 |
|
if link.endpoint_a.link and link == link.endpoint_a.link: |
755
|
1 |
|
switch = link.endpoint_a.switch |
756
|
1 |
|
link.endpoint_a.link = None |
757
|
1 |
|
link.endpoint_a.nni = False |
758
|
1 |
|
self.topo_controller.upsert_switch( |
759
|
|
|
switch.id, switch.as_dict() |
760
|
|
|
) |
761
|
1 |
|
if link.endpoint_b.link and link == link.endpoint_b.link: |
762
|
1 |
|
switch = link.endpoint_b.switch |
763
|
1 |
|
link.endpoint_b.link = None |
764
|
1 |
|
link.endpoint_b.nni = False |
765
|
1 |
|
self.topo_controller.upsert_switch( |
766
|
|
|
switch.id, switch.as_dict() |
767
|
|
|
) |
768
|
1 |
|
self.topo_controller.delete_link(link_id) |
769
|
1 |
|
link = self.controller.links.pop(link_id) |
770
|
1 |
|
self.notify_topology_update() |
771
|
1 |
|
name = 'kytos/topology.link.deleted' |
772
|
1 |
|
event = KytosEvent(name=name, content={'link': link}) |
773
|
1 |
|
self.controller.buffers.app.put(event) |
774
|
1 |
|
return JSONResponse("Operation successful") |
775
|
|
|
|
776
|
1 |
|
@rest('v3/interfaces/{intf_id}', methods=['DELETE']) |
777
|
1 |
|
def delete_interface(self, request: Request) -> JSONResponse: |
778
|
|
|
"""Delete an interface only if it is not used.""" |
779
|
1 |
|
intf_id = request.path_params.get("intf_id") |
780
|
1 |
|
intf_split = intf_id.split(":") |
781
|
1 |
|
switch_id = ":".join(intf_split[:-1]) |
782
|
1 |
|
try: |
783
|
1 |
|
intf_port = int(intf_split[-1]) |
784
|
1 |
|
except ValueError: |
785
|
1 |
|
raise HTTPException(400, detail="Invalid interface id.") |
786
|
1 |
|
try: |
787
|
1 |
|
switch = self.controller.switches[switch_id] |
788
|
1 |
|
except KeyError: |
789
|
1 |
|
raise HTTPException(404, detail="Switch not found.") |
790
|
1 |
|
try: |
791
|
1 |
|
interface = switch.interfaces[intf_port] |
792
|
1 |
|
except KeyError: |
793
|
1 |
|
raise HTTPException(404, detail="Interface not found.") |
794
|
|
|
|
795
|
1 |
|
usage = self.get_intf_usage(interface) |
796
|
1 |
|
if usage: |
797
|
1 |
|
raise HTTPException(409, detail=f"Interface could not be " |
798
|
|
|
f"deleted. Reason: {usage}") |
799
|
1 |
|
self._delete_interface(interface) |
800
|
1 |
|
name = "kytos/topology.interface.deleted" |
801
|
1 |
|
event = KytosEvent(name=name, content={"interface": interface}) |
802
|
1 |
|
self.controller.buffers.app.put(event) |
803
|
1 |
|
return JSONResponse("Operation Successful", status_code=200) |
804
|
|
|
|
805
|
1 |
|
@listen_to( |
806
|
|
|
"kytos/.*.liveness.(up|down|disabled)", |
807
|
|
|
pool="dynamic_single" |
808
|
|
|
) |
809
|
1 |
|
def on_link_liveness(self, event) -> None: |
810
|
|
|
"""Handle link liveness up|down|disabled event.""" |
811
|
|
|
liveness_status = event.name.split(".")[-1] |
812
|
|
|
if liveness_status == "disabled": |
813
|
|
|
interfaces = event.content["interfaces"] |
814
|
|
|
self.handle_link_liveness_disabled(interfaces) |
815
|
|
|
elif liveness_status in ("up", "down"): |
816
|
|
|
intf_a: Interface = event.content["interface_a"] |
817
|
|
|
intf_b: Interface = event.content["interface_b"] |
818
|
|
|
if (intf_a.link is None or |
819
|
|
|
intf_b.link is None or |
820
|
|
|
intf_a.link != intf_b.link): |
821
|
|
|
log.error("Link from interfaces " |
822
|
|
|
f"{intf_a}, {intf_b}" |
823
|
|
|
"not found.") |
824
|
|
|
return |
825
|
|
|
self.handle_link_liveness_status(intf_a.link, liveness_status) |
826
|
|
|
|
827
|
1 |
|
def handle_link_liveness_status( |
828
|
|
|
self, |
829
|
|
|
link: Link, |
830
|
|
|
liveness_status: str |
831
|
|
|
) -> None: |
832
|
|
|
"""Handle link liveness.""" |
833
|
1 |
|
with link.link_lock: |
834
|
1 |
|
metadata = {"liveness_status": liveness_status} |
835
|
1 |
|
log.info(f"Link liveness {liveness_status}: {link}") |
836
|
1 |
|
link.extend_metadata(metadata) |
837
|
1 |
|
self.notify_topology_update() |
838
|
1 |
|
if link.status == EntityStatus.UP and liveness_status == "up": |
839
|
1 |
|
self.notify_link_status_change(link, reason="liveness_up") |
840
|
1 |
|
if link.status == EntityStatus.DOWN and liveness_status == "down": |
841
|
1 |
|
self.notify_link_status_change(link, reason="liveness_down") |
842
|
|
|
|
843
|
1 |
|
def handle_link_liveness_disabled(self, interfaces) -> None: |
844
|
|
|
"""Handle link liveness disabled.""" |
845
|
1 |
|
log.info(f"Link liveness disabled interfaces: {interfaces}") |
846
|
|
|
|
847
|
1 |
|
key = "liveness_status" |
848
|
1 |
|
links = self.controller.get_links_from_interfaces(interfaces) |
849
|
1 |
|
with ExitStack() as stack: |
850
|
1 |
|
for link in links.values(): |
851
|
1 |
|
stack.enter_context(link.link_lock) |
852
|
1 |
|
link.remove_metadata(key) |
853
|
1 |
|
self.notify_topology_update() |
854
|
1 |
|
for link in links.values(): |
855
|
1 |
|
self.notify_link_status_change( |
856
|
|
|
link, reason="liveness_disabled" |
857
|
|
|
) |
858
|
|
|
|
859
|
1 |
|
@listen_to("kytos/core.interface_tags") |
860
|
1 |
|
def on_interface_tags(self, event): |
861
|
|
|
"""Handle on_interface_tags.""" |
862
|
|
|
interface = event.content['interface'] |
863
|
|
|
with self._intfs_lock[interface.id]: |
864
|
|
|
if ( |
865
|
|
|
interface.id in self._intfs_tags_updated_at |
866
|
|
|
and self._intfs_tags_updated_at[interface.id] > event.timestamp |
867
|
|
|
): |
868
|
|
|
return |
869
|
|
|
self._intfs_tags_updated_at[interface.id] = event.timestamp |
870
|
|
|
self.handle_on_interface_tags(interface) |
871
|
|
|
|
872
|
1 |
|
def handle_on_interface_tags(self, interface): |
873
|
|
|
"""Update interface details""" |
874
|
1 |
|
intf_id = interface.id |
875
|
1 |
|
self.topo_controller.upsert_interface_details( |
876
|
|
|
intf_id, interface.available_tags, interface.tag_ranges, |
877
|
|
|
interface.special_available_tags, |
878
|
|
|
interface.special_tags |
879
|
|
|
) |
880
|
|
|
|
881
|
1 |
|
@listen_to('.*.switch.(new|reconnected)') |
882
|
1 |
|
def on_new_switch(self, event): |
883
|
|
|
"""Create a new Device on the Topology. |
884
|
|
|
|
885
|
|
|
Handle the event of a new created switch and update the topology with |
886
|
|
|
this new device. Also notify if the switch is enabled. |
887
|
|
|
""" |
888
|
|
|
self.handle_new_switch(event) |
889
|
|
|
|
890
|
1 |
|
def handle_new_switch(self, event): |
891
|
|
|
"""Create a new Device on the Topology.""" |
892
|
1 |
|
switch = event.content['switch'] |
893
|
1 |
|
switch.activate() |
894
|
1 |
|
self.topo_controller.upsert_switch(switch.id, switch.as_dict()) |
895
|
1 |
|
log.debug('Switch %s added to the Topology.', switch.id) |
896
|
1 |
|
self.notify_topology_update() |
897
|
1 |
|
if switch.is_enabled(): |
898
|
1 |
|
self.notify_switch_enabled(switch.id) |
899
|
|
|
|
900
|
1 |
|
@listen_to('.*.connection.lost') |
901
|
1 |
|
def on_connection_lost(self, event): |
902
|
|
|
"""Remove a Device from the topology. |
903
|
|
|
|
904
|
|
|
Remove the disconnected Device and every link that has one of its |
905
|
|
|
interfaces. |
906
|
|
|
""" |
907
|
|
|
self.handle_connection_lost(event) |
908
|
|
|
|
909
|
1 |
|
def handle_connection_lost(self, event): |
910
|
|
|
"""Remove a Device from the topology.""" |
911
|
1 |
|
switch = event.content['source'].switch |
912
|
1 |
|
if switch: |
913
|
1 |
|
switch.deactivate() |
914
|
1 |
|
log.debug('Switch %s removed from the Topology.', switch.id) |
915
|
1 |
|
self.notify_topology_update() |
916
|
|
|
|
917
|
1 |
|
def handle_interfaces_created(self, event): |
918
|
|
|
"""Update the topology based on the interfaces created.""" |
919
|
1 |
|
interfaces = event.content["interfaces"] |
920
|
1 |
|
if not interfaces: |
921
|
|
|
return |
922
|
1 |
|
switch = interfaces[0].switch |
923
|
1 |
|
self.topo_controller.upsert_switch(switch.id, switch.as_dict()) |
924
|
1 |
|
name = "kytos/topology.switch.interface.created" |
925
|
1 |
|
for interface in interfaces: |
926
|
1 |
|
event = KytosEvent(name=name, content={'interface': interface}) |
927
|
1 |
|
self.controller.buffers.app.put(event) |
928
|
|
|
|
929
|
1 |
|
def handle_interface_created(self, event): |
930
|
|
|
"""Update the topology based on an interface created event. |
931
|
|
|
|
932
|
|
|
It's handled as a link_up in case a switch send a |
933
|
|
|
created event again and it can be belong to a link. |
934
|
|
|
""" |
935
|
1 |
|
interface = event.content['interface'] |
936
|
1 |
|
if not interface.is_active(): |
937
|
1 |
|
self.handle_interface_link_down(interface, event) |
938
|
|
|
else: |
939
|
1 |
|
self.handle_interface_link_up(interface, event) |
940
|
|
|
|
941
|
1 |
|
@listen_to('.*.topology.switch.interface.created') |
942
|
1 |
|
def on_interface_created(self, event): |
943
|
|
|
"""Handle individual interface create event. |
944
|
|
|
|
945
|
|
|
It's handled as a link_up in case a switch send a |
946
|
|
|
created event it can belong to an existign link. |
947
|
|
|
""" |
948
|
|
|
self.handle_interface_created(event) |
949
|
|
|
|
950
|
1 |
|
@listen_to('.*.switch.interfaces.created') |
951
|
1 |
|
def on_interfaces_created(self, event): |
952
|
|
|
"""Update the topology based on a list of created interfaces.""" |
953
|
|
|
self.handle_interfaces_created(event) |
954
|
|
|
|
955
|
1 |
|
def handle_interface_down(self, event): |
956
|
|
|
"""Update the topology based on a Port Modify event. |
957
|
|
|
|
958
|
|
|
The event notifies that an interface was changed to 'down'. |
959
|
|
|
""" |
960
|
1 |
|
interface = event.content['interface'] |
961
|
1 |
|
with self._intfs_lock[interface.id]: |
962
|
1 |
|
if ( |
963
|
|
|
interface.id in self._intfs_updated_at |
964
|
|
|
and self._intfs_updated_at[interface.id] > event.timestamp |
965
|
|
|
): |
966
|
|
|
return |
967
|
1 |
|
self._intfs_updated_at[interface.id] = event.timestamp |
968
|
1 |
|
interface.deactivate() |
969
|
1 |
|
self.handle_interface_link_down(interface, event) |
970
|
|
|
|
971
|
1 |
|
@listen_to('.*.switch.interface.deleted') |
972
|
1 |
|
def on_interface_deleted(self, event): |
973
|
|
|
"""Update the topology based on a Port Delete event.""" |
974
|
|
|
self.handle_interface_deleted(event) |
975
|
|
|
|
976
|
1 |
|
def handle_interface_deleted(self, event): |
977
|
|
|
"""Update the topology based on a Port Delete event.""" |
978
|
1 |
|
self.handle_interface_down(event) |
979
|
1 |
|
interface = event.content['interface'] |
980
|
1 |
|
usage = self.get_intf_usage(interface) |
981
|
1 |
|
if usage: |
982
|
1 |
|
log.info(f"Interface {interface.id} could not be safely removed." |
983
|
|
|
f" Reason: {usage}") |
984
|
|
|
else: |
985
|
1 |
|
self._delete_interface(interface) |
986
|
|
|
|
987
|
1 |
|
def get_intf_usage(self, interface: Interface) -> Optional[str]: |
988
|
|
|
"""Determines how an interface is used explained in a string, |
989
|
|
|
returns None if unused.""" |
990
|
1 |
|
if interface.is_enabled() or interface.is_active(): |
991
|
1 |
|
return "It is enabled or active." |
992
|
|
|
|
993
|
1 |
|
link = interface.link |
994
|
1 |
|
if link: |
995
|
1 |
|
return f"It has a link, {link.id}." |
996
|
|
|
|
997
|
1 |
|
flow_id = self.get_flow_id_by_intf(interface) |
998
|
1 |
|
if flow_id: |
999
|
1 |
|
return f"There is a flow installed, {flow_id}." |
1000
|
|
|
|
1001
|
1 |
|
return None |
1002
|
|
|
|
1003
|
1 |
|
def get_flow_id_by_intf(self, interface: Interface) -> str: |
1004
|
|
|
"""Return flow_id from first found flow used by interface.""" |
1005
|
1 |
|
flows = self.get_flows_by_switch(interface.switch.id) |
1006
|
1 |
|
port_n = int(interface.id.split(":")[-1]) |
1007
|
1 |
|
for flow in flows: |
1008
|
1 |
|
in_port = flow["flow"].get("match", {}).get("in_port") |
1009
|
1 |
|
if in_port == port_n: |
1010
|
1 |
|
return flow["flow_id"] |
1011
|
|
|
|
1012
|
1 |
|
instructions = flow["flow"].get("instructions", []) |
1013
|
1 |
|
for instruction in instructions: |
1014
|
1 |
|
if instruction["instruction_type"] == "apply_actions": |
1015
|
1 |
|
actions = instruction["actions"] |
1016
|
1 |
|
for action in actions: |
1017
|
1 |
|
if (action["action_type"] == "output" |
1018
|
|
|
and action.get("port") == port_n): |
1019
|
1 |
|
return flow["flow_id"] |
1020
|
|
|
|
1021
|
1 |
|
actions = flow["flow"].get("actions", []) |
1022
|
1 |
|
for action in actions: |
1023
|
1 |
|
if (action["action_type"] == "output" |
1024
|
|
|
and action.get("port") == port_n): |
1025
|
1 |
|
return flow["flow_id"] |
1026
|
1 |
|
return None |
1027
|
|
|
|
1028
|
1 |
|
def _delete_interface(self, interface: Interface): |
1029
|
|
|
"""Delete any trace of an interface. Only use this method when |
1030
|
|
|
it was confirmed that the interface is not used.""" |
1031
|
1 |
|
switch: Switch = interface.switch |
1032
|
1 |
|
switch.remove_interface(interface) |
1033
|
1 |
|
self.topo_controller.upsert_switch(switch.id, switch.as_dict()) |
1034
|
1 |
|
self.topo_controller.delete_interface_from_details(interface.id) |
1035
|
|
|
|
1036
|
1 |
|
@listen_to('.*.switch.interface.link_up') |
1037
|
1 |
|
def on_interface_link_up(self, event): |
1038
|
|
|
"""Update the topology based on a Port Modify event. |
1039
|
|
|
|
1040
|
|
|
The event notifies that an interface's link was changed to 'up'. |
1041
|
|
|
""" |
1042
|
|
|
interface = event.content['interface'] |
1043
|
|
|
self.handle_interface_link_up(interface, event) |
1044
|
|
|
|
1045
|
1 |
|
def handle_interface_link_up(self, interface, event): |
1046
|
|
|
"""Update the topology based on a Port Modify event.""" |
1047
|
1 |
|
with self._intfs_lock[interface.id]: |
1048
|
1 |
|
if ( |
1049
|
|
|
interface.id in self._intfs_updated_at |
1050
|
|
|
and self._intfs_updated_at[interface.id] > event.timestamp |
1051
|
|
|
): |
1052
|
1 |
|
return |
1053
|
1 |
|
self._intfs_updated_at[interface.id] = event.timestamp |
1054
|
1 |
|
self.handle_link_up(interface) |
1055
|
|
|
|
1056
|
1 |
|
@tenacity.retry( |
1057
|
|
|
stop=stop_after_attempt(3), |
1058
|
|
|
wait=wait_combine(wait_fixed(3), wait_random(min=2, max=7)), |
1059
|
|
|
before_sleep=before_sleep, |
1060
|
|
|
retry=retry_if_exception_type(httpx.RequestError), |
1061
|
|
|
) |
1062
|
1 |
|
def get_flows_by_switch(self, dpid: str) -> list: |
1063
|
|
|
"""Get installed flows by switch from flow_manager.""" |
1064
|
1 |
|
endpoint = settings.FLOW_MANAGER_URL +\ |
1065
|
|
|
f'/stored_flows?state=installed&dpid={dpid}' |
1066
|
1 |
|
res = httpx.get(endpoint) |
1067
|
1 |
|
if res.is_server_error or res.status_code in (404, 400): |
1068
|
1 |
|
raise httpx.RequestError(res.text) |
1069
|
1 |
|
return res.json().get(dpid, []) |
1070
|
|
|
|
1071
|
1 |
|
def link_status_hook_link_up_timer( |
1072
|
|
|
self, |
1073
|
|
|
link: Link |
1074
|
|
|
) -> Optional[EntityStatus]: |
1075
|
|
|
"""Link status hook link up timer.""" |
1076
|
1 |
|
tnow = time.time() |
1077
|
1 |
|
if link.id not in self.link_status_change: |
1078
|
|
|
return None |
1079
|
1 |
|
link_status_info = self.link_status_change[link.id] |
1080
|
1 |
|
tdelta = tnow - link_status_info['last_status_change'] |
1081
|
1 |
|
if tdelta < self.link_up_timer: |
1082
|
1 |
|
return EntityStatus.DOWN |
1083
|
1 |
|
return None |
1084
|
|
|
|
1085
|
1 |
|
@staticmethod |
1086
|
1 |
|
def detect_mismatched_link(link: Link) -> frozenset[str]: |
1087
|
|
|
"""Check if a link is mismatched.""" |
1088
|
1 |
|
if (link.endpoint_a.link and link.endpoint_b |
1089
|
|
|
and link.endpoint_a.link == link.endpoint_b.link): |
1090
|
1 |
|
return frozenset() |
1091
|
1 |
|
return frozenset(["mismatched_link"]) |
1092
|
|
|
|
1093
|
1 |
|
def link_status_mismatched(self, link: Link) -> Optional[EntityStatus]: |
1094
|
|
|
"""Check if a link is mismatched and return a status.""" |
1095
|
1 |
|
if self.detect_mismatched_link(link): |
1096
|
1 |
|
return EntityStatus.DOWN |
1097
|
1 |
|
return None |
1098
|
|
|
|
1099
|
1 |
|
def notify_link_up_if_status(self, link: Link, reason="link up") -> None: |
1100
|
|
|
"""Tries to notify link up and topology changes based on its status |
1101
|
|
|
|
1102
|
|
|
Currently, it needs to wait up to a timer.""" |
1103
|
1 |
|
time.sleep(self.link_up_timer) |
1104
|
1 |
|
if link.status != EntityStatus.UP: |
1105
|
|
|
return |
1106
|
1 |
|
with link.link_lock: |
1107
|
1 |
|
status_change_info = self.link_status_change[link.id] |
1108
|
1 |
|
notified_at = status_change_info.get("notified_up_at") |
1109
|
1 |
|
if ( |
1110
|
|
|
notified_at |
1111
|
|
|
and (now() - notified_at.replace(tzinfo=timezone.utc)).seconds |
1112
|
|
|
< self.link_up_timer |
1113
|
|
|
): |
1114
|
1 |
|
return |
1115
|
1 |
|
status_change_info["notified_up_at"] = now() |
1116
|
1 |
|
self.notify_topology_update() |
1117
|
1 |
|
self.notify_link_status_change(link, reason) |
1118
|
|
|
|
1119
|
1 |
|
def handle_link_up(self, interface: Interface): |
1120
|
|
|
"""Handle link up for an interface.""" |
1121
|
1 |
|
link = interface.link |
1122
|
1 |
|
if not link: |
1123
|
|
|
self.notify_topology_update() |
1124
|
|
|
return |
1125
|
1 |
|
with link.link_lock: |
1126
|
1 |
|
other_interface = ( |
1127
|
|
|
link.endpoint_b if link.endpoint_a == interface |
1128
|
|
|
else link.endpoint_a |
1129
|
|
|
) |
1130
|
1 |
|
if ( |
1131
|
|
|
link.id not in self.link_status_change or |
1132
|
|
|
not link.is_active() |
1133
|
|
|
): |
1134
|
1 |
|
status_change_info = self.link_status_change[link.id] |
1135
|
1 |
|
status_change_info['last_status_change'] = time.time() |
1136
|
1 |
|
link.activate() |
1137
|
1 |
|
self.notify_topology_update() |
1138
|
1 |
|
link_dependencies: list[GenericEntity] = [ |
1139
|
|
|
other_interface.switch, |
1140
|
|
|
interface.switch, |
1141
|
|
|
other_interface, |
1142
|
|
|
interface, |
1143
|
|
|
] |
1144
|
1 |
|
for dependency in link_dependencies: |
1145
|
1 |
|
if not dependency.is_active(): |
1146
|
1 |
|
log.info( |
1147
|
|
|
f"{link} dependency {dependency} was not active yet." |
1148
|
|
|
) |
1149
|
1 |
|
return |
1150
|
1 |
|
event = KytosEvent( |
1151
|
|
|
name="kytos/topology.notify_link_up_if_status", |
1152
|
|
|
content={"reason": "link up", "link": link} |
1153
|
|
|
) |
1154
|
1 |
|
self.controller.buffers.app.put(event) |
1155
|
|
|
|
1156
|
1 |
|
@listen_to('.*.switch.interface.link_down') |
1157
|
1 |
|
def on_interface_link_down(self, event: KytosEvent): |
1158
|
|
|
"""Update the topology based on a Port Modify event. |
1159
|
|
|
|
1160
|
|
|
The event notifies that an interface's link was changed to 'down'. |
1161
|
|
|
""" |
1162
|
|
|
interface = event.content['interface'] |
1163
|
|
|
self.handle_interface_link_down(interface, event) |
1164
|
|
|
|
1165
|
1 |
|
def handle_interface_link_down( |
1166
|
|
|
self, |
1167
|
|
|
interface: Interface, |
1168
|
|
|
event: KytosEvent |
1169
|
|
|
): |
1170
|
|
|
"""Update the topology based on an interface.""" |
1171
|
1 |
|
with self._intfs_lock[interface.id]: |
1172
|
1 |
|
if ( |
1173
|
|
|
interface.id in self._intfs_updated_at |
1174
|
|
|
and self._intfs_updated_at[interface.id] > event.timestamp |
1175
|
|
|
): |
1176
|
1 |
|
return |
1177
|
1 |
|
self._intfs_updated_at[interface.id] = event.timestamp |
1178
|
1 |
|
self.handle_link_down(interface) |
1179
|
|
|
|
1180
|
1 |
|
def handle_link_down(self, interface): |
1181
|
|
|
"""Notify a link is down.""" |
1182
|
1 |
|
link = interface.link |
1183
|
1 |
|
if link: |
1184
|
1 |
|
with link.link_lock: |
1185
|
1 |
|
link.deactivate() |
1186
|
1 |
|
self.notify_link_status_change(link, reason="link down") |
1187
|
1 |
|
self.notify_topology_update() |
1188
|
|
|
|
1189
|
1 |
|
@listen_to('.*.interface.is.nni') |
1190
|
1 |
|
def on_add_links(self, event): |
1191
|
|
|
"""Update the topology with links related to the NNI interfaces.""" |
1192
|
|
|
self.add_links(event) |
1193
|
|
|
|
1194
|
1 |
|
def add_links(self, event): |
1195
|
|
|
"""Update the topology with links related to the NNI interfaces.""" |
1196
|
1 |
|
interface_a: Interface = event.content['interface_a'] |
1197
|
1 |
|
interface_b: Interface = event.content['interface_b'] |
1198
|
|
|
|
1199
|
1 |
|
try: |
1200
|
1 |
|
link, created = self.controller.get_link_or_create(interface_a, |
1201
|
|
|
interface_b) |
1202
|
|
|
|
1203
|
|
|
except KytosLinkCreationError as err: |
1204
|
|
|
log.error(f'Error creating link: {err}.') |
1205
|
|
|
return |
1206
|
|
|
|
1207
|
1 |
|
if not created: |
1208
|
|
|
return |
1209
|
1 |
|
self.notify_topology_update() |
1210
|
|
|
|
1211
|
1 |
|
with link.link_lock: |
1212
|
1 |
|
if link.is_active() and link.id not in self.link_status_change: |
1213
|
1 |
|
status_change_info = self.link_status_change[link.id] |
1214
|
1 |
|
status_change_info['last_status_change'] = time.time() |
1215
|
1 |
|
self.topo_controller.upsert_link(link.id, link.as_dict()) |
1216
|
1 |
|
self.notify_link_up_if_status(link, "link up") |
1217
|
|
|
|
1218
|
1 |
|
@listen_to('.*.of_lldp.network_status.updated') |
1219
|
1 |
|
def on_lldp_status_updated(self, event): |
1220
|
|
|
"""Handle of_lldp.network_status.updated from of_lldp.""" |
1221
|
|
|
self.handle_lldp_status_updated(event) |
1222
|
|
|
|
1223
|
1 |
|
@listen_to(".*.topo_controller.upsert_switch") |
1224
|
1 |
|
def on_topo_controller_upsert_switch(self, event) -> None: |
1225
|
|
|
"""Listen to topo_controller_upsert_switch.""" |
1226
|
|
|
self.handle_topo_controller_upsert_switch(event.content["switch"]) |
1227
|
|
|
|
1228
|
1 |
|
def handle_topo_controller_upsert_switch(self, switch) -> Optional[dict]: |
1229
|
|
|
"""Handle topo_controller_upsert_switch.""" |
1230
|
1 |
|
return self.topo_controller.upsert_switch(switch.id, switch.as_dict()) |
1231
|
|
|
|
1232
|
1 |
|
def handle_lldp_status_updated(self, event) -> None: |
1233
|
|
|
"""Handle .*.network_status.updated events from of_lldp.""" |
1234
|
1 |
|
content = event.content |
1235
|
1 |
|
interface_ids = content["interface_ids"] |
1236
|
1 |
|
switches = set() |
1237
|
1 |
|
for interface_id in interface_ids: |
1238
|
1 |
|
dpid = ":".join(interface_id.split(":")[:-1]) |
1239
|
1 |
|
switch = self.controller.get_switch_by_dpid(dpid) |
1240
|
1 |
|
if switch: |
1241
|
1 |
|
switches.add(switch) |
1242
|
|
|
|
1243
|
1 |
|
name = "kytos/topology.topo_controller.upsert_switch" |
1244
|
1 |
|
for switch in switches: |
1245
|
1 |
|
event = KytosEvent(name=name, content={"switch": switch}) |
1246
|
1 |
|
self.controller.buffers.app.put(event) |
1247
|
|
|
|
1248
|
1 |
|
def notify_switch_enabled(self, dpid): |
1249
|
|
|
"""Send an event to notify that a switch is enabled.""" |
1250
|
1 |
|
name = 'kytos/topology.switch.enabled' |
1251
|
1 |
|
event = KytosEvent(name=name, content={'dpid': dpid}) |
1252
|
1 |
|
self.controller.buffers.app.put(event) |
1253
|
|
|
|
1254
|
1 |
|
def notify_switch_links_status(self, switch, reason): |
1255
|
|
|
"""Send an event to notify the status of a link in a switch""" |
1256
|
1 |
|
for link in self.controller.links.copy().values(): |
1257
|
1 |
|
with link.link_lock: |
1258
|
1 |
|
if switch in (link.endpoint_a.switch, link.endpoint_b.switch): |
1259
|
1 |
|
if reason == "link enabled": |
1260
|
1 |
|
name = 'kytos/topology.notify_link_up_if_status' |
1261
|
1 |
|
content = {'reason': reason, "link": link} |
1262
|
1 |
|
event = KytosEvent(name=name, content=content) |
1263
|
1 |
|
self.controller.buffers.app.put(event) |
1264
|
|
|
else: |
1265
|
1 |
|
self.notify_link_status_change(link, reason) |
1266
|
|
|
|
1267
|
1 |
|
def notify_switch_disabled(self, dpid): |
1268
|
|
|
"""Send an event to notify that a switch is disabled.""" |
1269
|
1 |
|
name = 'kytos/topology.switch.disabled' |
1270
|
1 |
|
event = KytosEvent(name=name, content={'dpid': dpid}) |
1271
|
1 |
|
self.controller.buffers.app.put(event) |
1272
|
|
|
|
1273
|
1 |
|
def notify_topology_update(self): |
1274
|
|
|
"""Send an event to notify about updates on the topology.""" |
1275
|
1 |
|
name = 'kytos/topology.updated' |
1276
|
1 |
|
next_topology = self._get_topology() |
1277
|
1 |
|
event = KytosEvent( |
1278
|
|
|
name=name, content={'topology': self._get_topology()} |
1279
|
|
|
) |
1280
|
1 |
|
self.controller.buffers.app.put(event) |
1281
|
1 |
|
self.last_pushed_topology = next_topology |
1282
|
|
|
|
1283
|
1 |
|
def _notify_interface_link_status( |
1284
|
|
|
self, |
1285
|
|
|
interfaces: Iterable[Interface], |
1286
|
|
|
reason |
1287
|
|
|
): |
1288
|
|
|
"""Send an event to notify the status of a link from interfaces.""" |
1289
|
1 |
|
for interface in interfaces: |
1290
|
1 |
|
if interface.link: |
1291
|
1 |
|
if reason == "link enabled": |
1292
|
1 |
|
name = 'kytos/topology.notify_link_up_if_status' |
1293
|
1 |
|
content = {'reason': reason, "link": interface.link} |
1294
|
1 |
|
event = KytosEvent(name=name, content=content) |
1295
|
1 |
|
self.controller.buffers.app.put(event) |
1296
|
|
|
else: |
1297
|
1 |
|
self.notify_link_status_change(interface.link, reason) |
1298
|
|
|
|
1299
|
1 |
|
def notify_link_status_change(self, link: Link, reason='not given'): |
1300
|
|
|
"""Send an event to notify (up/down) from a status change on |
1301
|
|
|
a link.""" |
1302
|
1 |
|
link_id = link.id |
1303
|
1 |
|
with self.link_status_lock: |
1304
|
1 |
|
if ( |
1305
|
|
|
(not link.status_reason and link.status == EntityStatus.UP) |
1306
|
|
|
and link_id not in self.link_up |
1307
|
|
|
): |
1308
|
1 |
|
log.info(f"{link} changed status {link.status}, " |
1309
|
|
|
f"reason: {reason}") |
1310
|
1 |
|
self.link_up.add(link_id) |
1311
|
1 |
|
event = KytosEvent( |
1312
|
|
|
name='kytos/topology.link_up', |
1313
|
|
|
content={ |
1314
|
|
|
'link': link, |
1315
|
|
|
'reason': reason |
1316
|
|
|
}, |
1317
|
|
|
) |
1318
|
1 |
|
elif ( |
1319
|
|
|
(link.status_reason or link.status != EntityStatus.UP) |
1320
|
|
|
and link_id in self.link_up |
1321
|
|
|
): |
1322
|
1 |
|
log.info(f"{link} changed status {link.status}, " |
1323
|
|
|
f"reason: {reason}") |
1324
|
1 |
|
self.link_up.remove(link_id) |
1325
|
1 |
|
event = KytosEvent( |
1326
|
|
|
name='kytos/topology.link_down', |
1327
|
|
|
content={ |
1328
|
|
|
'link': link, |
1329
|
|
|
'reason': reason |
1330
|
|
|
}, |
1331
|
|
|
) |
1332
|
|
|
else: |
1333
|
1 |
|
return |
1334
|
1 |
|
self.controller.buffers.app.put(event) |
1335
|
|
|
|
1336
|
1 |
|
def notify_metadata_changes(self, obj, action): |
1337
|
|
|
"""Send an event to notify about metadata changes.""" |
1338
|
1 |
|
if isinstance(obj, Switch): |
1339
|
1 |
|
entity = 'switch' |
1340
|
1 |
|
entities = 'switches' |
1341
|
1 |
|
elif isinstance(obj, Interface): |
1342
|
1 |
|
entity = 'interface' |
1343
|
1 |
|
entities = 'interfaces' |
1344
|
1 |
|
elif isinstance(obj, Link): |
1345
|
1 |
|
entity = 'link' |
1346
|
1 |
|
entities = 'links' |
1347
|
|
|
else: |
1348
|
1 |
|
raise ValueError( |
1349
|
|
|
'Invalid object, supported: Switch, Interface, Link' |
1350
|
|
|
) |
1351
|
|
|
|
1352
|
1 |
|
name = f'kytos/topology.{entities}.metadata.{action}' |
1353
|
1 |
|
content = {entity: obj, 'metadata': obj.metadata.copy()} |
1354
|
1 |
|
event = KytosEvent(name=name, content=content) |
1355
|
1 |
|
self.controller.buffers.app.put(event) |
1356
|
1 |
|
log.debug(f'Metadata from {obj.id} was {action}.') |
1357
|
|
|
|
1358
|
1 |
|
@listen_to('kytos/topology.notify_link_up_if_status') |
1359
|
1 |
|
def on_notify_link_up_if_status(self, event): |
1360
|
|
|
"""Tries to notify link up and topology changes""" |
1361
|
|
|
link = event.content["link"] |
1362
|
|
|
reason = event.content["reason"] |
1363
|
|
|
self.notify_link_up_if_status(link, reason) |
1364
|
|
|
|
1365
|
1 |
|
@listen_to('.*.switch.port.created') |
1366
|
1 |
|
def on_notify_port_created(self, event): |
1367
|
|
|
"""Notify when a port is created.""" |
1368
|
|
|
self.notify_port_created(event) |
1369
|
|
|
|
1370
|
1 |
|
def notify_port_created(self, event): |
1371
|
|
|
"""Notify when a port is created.""" |
1372
|
1 |
|
name = 'kytos/topology.port.created' |
1373
|
1 |
|
event = KytosEvent(name=name, content=event.content) |
1374
|
1 |
|
self.controller.buffers.app.put(event) |
1375
|
|
|
|
1376
|
1 |
|
@staticmethod |
1377
|
1 |
|
def load_interfaces_tags_values(switch: Switch, |
1378
|
|
|
interfaces_details: List[dict]) -> None: |
1379
|
|
|
"""Load interfaces available tags (vlans).""" |
1380
|
1 |
|
if not interfaces_details: |
1381
|
|
|
return |
1382
|
1 |
|
for interface_details in interfaces_details: |
1383
|
1 |
|
available_tags = interface_details['available_tags'] |
1384
|
1 |
|
if not available_tags: |
1385
|
|
|
continue |
1386
|
1 |
|
log.debug(f"Interface id {interface_details['id']} loading " |
1387
|
|
|
f"{len(available_tags)} " |
1388
|
|
|
"available tags") |
1389
|
1 |
|
port_number = int(interface_details["id"].split(":")[-1]) |
1390
|
1 |
|
interface = switch.interfaces[port_number] |
1391
|
1 |
|
interface.set_available_tags_tag_ranges( |
1392
|
|
|
available_tags, |
1393
|
|
|
interface_details['tag_ranges'], |
1394
|
|
|
interface_details['special_available_tags'], |
1395
|
|
|
interface_details['special_tags'], |
1396
|
|
|
) |
1397
|
|
|
|
1398
|
1 |
|
@listen_to( |
1399
|
|
|
'topology.interruption.(start|end)', |
1400
|
|
|
pool="dynamic_single" |
1401
|
|
|
) |
1402
|
1 |
|
def on_interruption(self, event: KytosEvent): |
1403
|
|
|
"""Deals with service interruptions.""" |
1404
|
|
|
_, _, interrupt_type = event.name.rpartition(".") |
1405
|
|
|
if interrupt_type == "start": |
1406
|
|
|
self.handle_interruption_start(event) |
1407
|
|
|
elif interrupt_type == "end": |
1408
|
|
|
self.handle_interruption_end(event) |
1409
|
|
|
|
1410
|
1 |
View Code Duplication |
def handle_interruption_start(self, event: KytosEvent): |
|
|
|
|
1411
|
|
|
"""Deals with the start of service interruption.""" |
1412
|
1 |
|
interrupt_type = event.content['type'] |
1413
|
1 |
|
switches = event.content.get('switches', []) |
1414
|
1 |
|
interfaces = event.content.get('interfaces', []) |
1415
|
1 |
|
links = event.content.get('links', []) |
1416
|
1 |
|
log.info( |
1417
|
|
|
'Received interruption start of type \'%s\' ' |
1418
|
|
|
'affecting switches %s, interfaces %s, links %s', |
1419
|
|
|
interrupt_type, |
1420
|
|
|
switches, |
1421
|
|
|
interfaces, |
1422
|
|
|
links |
1423
|
|
|
) |
1424
|
|
|
# for switch_id in switches: |
1425
|
|
|
# pass |
1426
|
|
|
# for interface_id in interfaces: |
1427
|
|
|
# pass |
1428
|
1 |
|
for link_id in links: |
1429
|
1 |
|
link = self.controller.get_link(link_id) |
1430
|
1 |
|
if link is None: |
1431
|
|
|
log.error( |
1432
|
|
|
"Invalid link id '%s' for interruption of type '%s;", |
1433
|
|
|
link_id, |
1434
|
|
|
interrupt_type |
1435
|
|
|
) |
1436
|
|
|
else: |
1437
|
1 |
|
with link.link_lock: |
1438
|
1 |
|
self.notify_link_status_change(link, interrupt_type) |
1439
|
1 |
|
self.notify_topology_update() |
1440
|
|
|
|
1441
|
1 |
View Code Duplication |
def handle_interruption_end(self, event: KytosEvent): |
|
|
|
|
1442
|
|
|
"""Deals with the end of service interruption.""" |
1443
|
1 |
|
interrupt_type = event.content['type'] |
1444
|
1 |
|
switches = event.content.get('switches', []) |
1445
|
1 |
|
interfaces = event.content.get('interfaces', []) |
1446
|
1 |
|
links = event.content.get('links', []) |
1447
|
1 |
|
log.info( |
1448
|
|
|
'Received interruption end of type \'%s\' ' |
1449
|
|
|
'affecting switches %s, interfaces %s, links %s', |
1450
|
|
|
interrupt_type, |
1451
|
|
|
switches, |
1452
|
|
|
interfaces, |
1453
|
|
|
links |
1454
|
|
|
) |
1455
|
|
|
# for switch_id in switches: |
1456
|
|
|
# pass |
1457
|
|
|
# for interface_id in interfaces: |
1458
|
|
|
# pass |
1459
|
1 |
|
for link_id in links: |
1460
|
1 |
|
link = self.controller.get_link(link_id) |
1461
|
1 |
|
if link is None: |
1462
|
|
|
log.error( |
1463
|
|
|
"Invalid link id '%s' for interruption of type '%s;", |
1464
|
|
|
link_id, |
1465
|
|
|
interrupt_type |
1466
|
|
|
) |
1467
|
|
|
else: |
1468
|
1 |
|
with link.link_lock: |
1469
|
1 |
|
self.notify_link_status_change(link, interrupt_type) |
1470
|
1 |
|
self.notify_topology_update() |
1471
|
|
|
|
1472
|
1 |
|
def get_latest_topology(self): |
1473
|
|
|
"""Get the latest topology.""" |
1474
|
|
|
with self.controller.links_lock: |
1475
|
|
|
return self.last_pushed_topology |
1476
|
|
|
|