forked from kytos-ng/mef_eline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
executable file
·1187 lines (1037 loc) · 44.7 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
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# pylint: disable=protected-access, too-many-lines
"""Main module of kytos/mef_eline Kytos Network Application.
NApp to provision circuits from user request.
"""
import pathlib
import time
import traceback
from collections import defaultdict
from copy import deepcopy
from threading import Lock
from typing import Optional
from pydantic import ValidationError
from kytos.core import KytosNApp, log, rest
from kytos.core.events import KytosEvent
from kytos.core.exceptions import KytosTagError
from kytos.core.helpers import (alisten_to, listen_to, load_spec, now,
validate_openapi)
from kytos.core.interface import TAG, UNI, TAGRange
from kytos.core.link import Link
from kytos.core.rest_api import (HTTPException, JSONResponse, Request,
get_json_or_400)
from kytos.core.tag_ranges import get_tag_ranges
from napps.kytos.mef_eline import controllers, settings
from napps.kytos.mef_eline.exceptions import (DisabledSwitch,
DuplicatedNoTagUNI, InvalidPath)
from napps.kytos.mef_eline.models import (EVC, DynamicPathManager, EVCDeploy,
Path)
from napps.kytos.mef_eline.scheduler import CircuitSchedule, Scheduler
from napps.kytos.mef_eline.utils import (aemit_event, check_disabled_component,
emit_event, get_vlan_tags_and_masks,
map_evc_event_content,
merge_flow_dicts, prepare_delete_flow,
send_flow_mods_event)
# pylint: disable=too-many-public-methods
class Main(KytosNApp):
"""Main class of amlight/mef_eline NApp.
This class is the entry point for this napp.
"""
spec = load_spec(pathlib.Path(__file__).parent / "openapi.yml")
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.
"""
# object used to scheduler circuit events
self.sched = Scheduler()
# object to save and load circuits
self.mongo_controller = self.get_eline_controller()
self.mongo_controller.bootstrap_indexes()
# set the controller that will manager the dynamic paths
DynamicPathManager.set_controller(self.controller)
# dictionary of EVCs created. It acts as a circuit buffer.
# Every create/update/delete must be synced to mongodb.
self.circuits = {}
self._intf_events = defaultdict(dict)
self._lock_interfaces = defaultdict(Lock)
self.table_group = {"epl": 0, "evpl": 0}
self._lock = Lock()
self.execute_as_loop(settings.DEPLOY_EVCS_INTERVAL)
self.load_all_evcs()
self._topology_updated_at = None
def get_evcs_by_svc_level(self, enable_filter: bool = True) -> list:
"""Get circuits sorted by desc service level and asc creation_time.
In the future, as more ops are offloaded it should be get from the DB.
"""
if enable_filter:
return sorted(
[circuit for circuit in self.circuits.values()
if circuit.is_enabled()],
key=lambda x: (-x.service_level, x.creation_time),
)
return sorted(self.circuits.values(),
key=lambda x: (-x.service_level, x.creation_time))
@staticmethod
def get_eline_controller():
"""Return the ELineController instance."""
return controllers.ELineController()
def execute(self):
"""Execute once when the napp is running."""
if self._lock.locked():
return
log.debug("Starting consistency routine")
with self._lock:
self.execute_consistency()
log.debug("Finished consistency routine")
def should_be_checked(self, circuit):
"Verify if the circuit meets the necessary conditions to be checked"
# pylint: disable=too-many-boolean-expressions
if (
circuit.is_enabled()
and not circuit.is_active()
and not circuit.lock.locked()
and not circuit.has_recent_removed_flow()
and not circuit.is_recent_updated()
and circuit.are_unis_active(self.controller.switches)
# if a inter-switch EVC does not have current_path, it does not
# make sense to run sdntrace on it
and (circuit.is_intra_switch() or circuit.current_path)
):
return True
return False
def execute_consistency(self):
"""Execute consistency routine."""
circuits_to_check = []
for circuit in self.get_evcs_by_svc_level(enable_filter=False):
if self.should_be_checked(circuit):
circuits_to_check.append(circuit)
circuit.try_setup_failover_path()
circuits_checked = EVCDeploy.check_list_traces(circuits_to_check)
for circuit in circuits_to_check:
is_checked = circuits_checked.get(circuit.id)
if is_checked:
circuit.execution_rounds = 0
log.info(f"{circuit} enabled but inactive - activating")
with circuit.lock:
circuit.activate()
circuit.sync()
else:
circuit.execution_rounds += 1
if circuit.execution_rounds > settings.WAIT_FOR_OLD_PATH:
log.info(f"{circuit} enabled but inactive - redeploy")
with circuit.lock:
circuit.deploy()
def shutdown(self):
"""Execute when your napp is unloaded.
If you have some cleanup procedure, insert it here.
"""
@rest("/v2/evc/", methods=["GET"])
def list_circuits(self, request: Request) -> JSONResponse:
"""Endpoint to return circuits stored.
archive query arg if defined (not null) will be filtered
accordingly, by default only non archived evcs will be listed
"""
log.debug("list_circuits /v2/evc")
args = request.query_params
archived = args.get("archived", "false").lower()
args = {k: v for k, v in args.items() if k not in {"archived"}}
circuits = self.mongo_controller.get_circuits(archived=archived,
metadata=args)
circuits = circuits['circuits']
return JSONResponse(circuits)
@rest("/v2/evc/schedule", methods=["GET"])
def list_schedules(self, _request: Request) -> JSONResponse:
"""Endpoint to return all schedules stored for all circuits.
Return a JSON with the following template:
[{"schedule_id": <schedule_id>,
"circuit_id": <circuit_id>,
"schedule": <schedule object>}]
"""
log.debug("list_schedules /v2/evc/schedule")
circuits = self.mongo_controller.get_circuits()['circuits'].values()
if not circuits:
result = {}
status = 200
return JSONResponse(result, status_code=status)
result = []
status = 200
for circuit in circuits:
circuit_scheduler = circuit.get("circuit_scheduler")
if circuit_scheduler:
for scheduler in circuit_scheduler:
value = {
"schedule_id": scheduler.get("id"),
"circuit_id": circuit.get("id"),
"schedule": scheduler,
}
result.append(value)
log.debug("list_schedules result %s %s", result, status)
return JSONResponse(result, status_code=status)
@rest("/v2/evc/{circuit_id}", methods=["GET"])
def get_circuit(self, request: Request) -> JSONResponse:
"""Endpoint to return a circuit based on id."""
circuit_id = request.path_params["circuit_id"]
log.debug("get_circuit /v2/evc/%s", circuit_id)
circuit = self.mongo_controller.get_circuit(circuit_id)
if not circuit:
result = f"circuit_id {circuit_id} not found"
log.debug("get_circuit result %s %s", result, 404)
raise HTTPException(404, detail=result)
status = 200
log.debug("get_circuit result %s %s", circuit, status)
return JSONResponse(circuit, status_code=status)
# pylint: disable=too-many-branches, too-many-statements
@rest("/v2/evc/", methods=["POST"])
@validate_openapi(spec)
def create_circuit(self, request: Request) -> JSONResponse:
"""Try to create a new circuit.
Firstly, for EVPL: E-Line NApp verifies if UNI_A's requested C-VID and
UNI_Z's requested C-VID are available from the interfaces' pools. This
is checked when creating the UNI object.
Then, E-Line NApp requests a primary and a backup path to the
Pathfinder NApp using the attributes primary_links and backup_links
submitted via REST
# For each link composing paths in #3:
# - E-Line NApp requests a S-VID available from the link VLAN pool.
# - Using the S-VID obtained, generate abstract flow entries to be
# sent to FlowManager
Push abstract flow entries to FlowManager and FlowManager pushes
OpenFlow entries to datapaths
E-Line NApp generates an event to notify all Kytos NApps of a new EVC
creation
Finnaly, notify user of the status of its request.
"""
# Try to create the circuit object
log.debug("create_circuit /v2/evc/")
data = get_json_or_400(request, self.controller.loop)
try:
evc = self._evc_from_dict(data)
except (ValueError, KytosTagError) as exception:
log.debug("create_circuit result %s %s", exception, 400)
raise HTTPException(400, detail=str(exception)) from exception
try:
check_disabled_component(evc.uni_a, evc.uni_z)
except DisabledSwitch as exception:
log.debug("create_circuit result %s %s", exception, 409)
raise HTTPException(
409,
detail=f"Path is not valid: {exception}"
) from exception
if evc.primary_path:
try:
evc.primary_path.is_valid(
evc.uni_a.interface.switch,
evc.uni_z.interface.switch,
bool(evc.circuit_scheduler),
)
except InvalidPath as exception:
raise HTTPException(
400,
detail=f"primary_path is not valid: {exception}"
) from exception
if evc.backup_path:
try:
evc.backup_path.is_valid(
evc.uni_a.interface.switch,
evc.uni_z.interface.switch,
bool(evc.circuit_scheduler),
)
except InvalidPath as exception:
raise HTTPException(
400,
detail=f"backup_path is not valid: {exception}"
) from exception
if not evc._tag_lists_equal():
detail = "UNI_A and UNI_Z tag lists should be the same."
raise HTTPException(400, detail=detail)
try:
evc._validate_has_primary_or_dynamic()
except ValueError as exception:
raise HTTPException(400, detail=str(exception)) from exception
try:
self._check_no_tag_duplication(evc.id, evc.uni_a, evc.uni_z)
except DuplicatedNoTagUNI as exception:
log.debug("create_circuit result %s %s", exception, 409)
raise HTTPException(409, detail=str(exception)) from exception
try:
self._use_uni_tags(evc)
except KytosTagError as exception:
raise HTTPException(400, detail=str(exception)) from exception
# save circuit
try:
evc.sync()
except ValidationError as exception:
raise HTTPException(400, detail=str(exception)) from exception
# store circuit in dictionary
self.circuits[evc.id] = evc
# Schedule the circuit deploy
self.sched.add(evc)
# Circuit has no schedule, deploy now
deployed = False
if not evc.circuit_scheduler:
with evc.lock:
deployed = evc.deploy()
# Notify users
result = {"circuit_id": evc.id, "deployed": deployed}
status = 201
log.debug("create_circuit result %s %s", result, status)
emit_event(self.controller, name="created",
content=map_evc_event_content(evc))
return JSONResponse(result, status_code=status)
@staticmethod
def _use_uni_tags(evc):
uni_a = evc.uni_a
evc._use_uni_vlan(uni_a)
try:
uni_z = evc.uni_z
evc._use_uni_vlan(uni_z)
except KytosTagError as err:
evc.make_uni_vlan_available(uni_a)
raise err
@listen_to('kytos/flow_manager.flow.removed')
def on_flow_delete(self, event):
"""Capture delete messages to keep track when flows got removed."""
self.handle_flow_delete(event)
def handle_flow_delete(self, event):
"""Keep track when the EVC got flows removed by deriving its cookie."""
flow = event.content["flow"]
evc = self.circuits.get(EVC.get_id_from_cookie(flow.cookie))
if evc:
log.debug("Flow removed in EVC %s", evc.id)
evc.set_flow_removed_at()
@rest("/v2/evc/{circuit_id}", methods=["PATCH"])
@validate_openapi(spec)
def update(self, request: Request) -> JSONResponse:
"""Update a circuit based on payload.
The EVC attributes (creation_time, active, current_path,
failover_path, _id, archived) can't be updated.
"""
data = get_json_or_400(request, self.controller.loop)
circuit_id = request.path_params["circuit_id"]
log.debug("update /v2/evc/%s", circuit_id)
try:
evc = self.circuits[circuit_id]
except KeyError:
result = f"circuit_id {circuit_id} not found"
log.debug("update result %s %s", result, 404)
raise HTTPException(404, detail=result) from KeyError
try:
updated_data = self._evc_dict_with_instances(data)
self._check_no_tag_duplication(
circuit_id, updated_data.get("uni_a"),
updated_data.get("uni_z")
)
enable, redeploy = evc.update(**updated_data)
except (ValueError, KytosTagError, ValidationError) as exception:
log.debug("update result %s %s", exception, 400)
raise HTTPException(400, detail=str(exception)) from exception
except DuplicatedNoTagUNI as exception:
log.debug("update result %s %s", exception, 409)
raise HTTPException(409, detail=str(exception)) from exception
except DisabledSwitch as exception:
log.debug("update result %s %s", exception, 409)
raise HTTPException(
409,
detail=f"Path is not valid: {exception}"
) from exception
redeployed = False
if evc.is_active():
if enable is False: # disable if active
with evc.lock:
evc.remove()
elif redeploy is not None: # redeploy if active
with evc.lock:
evc.remove()
redeployed = evc.deploy()
else:
if enable is True: # enable if inactive
with evc.lock:
redeployed = evc.deploy()
elif evc.is_enabled() and redeploy:
with evc.lock:
evc.remove()
redeployed = evc.deploy()
result = {evc.id: evc.as_dict(), 'redeployed': redeployed}
status = 200
log.debug("update result %s %s", result, status)
emit_event(self.controller, "updated",
content=map_evc_event_content(evc, **data))
return JSONResponse(result, status_code=status)
@rest("/v2/evc/{circuit_id}", methods=["DELETE"])
def delete_circuit(self, request: Request) -> JSONResponse:
"""Remove a circuit.
First, the flows are removed from the switches, and then the EVC is
disabled.
"""
circuit_id = request.path_params["circuit_id"]
log.debug("delete_circuit /v2/evc/%s", circuit_id)
try:
evc = self.circuits.pop(circuit_id)
except KeyError:
result = f"circuit_id {circuit_id} not found"
log.debug("delete_circuit result %s %s", result, 404)
raise HTTPException(404, detail=result) from KeyError
log.info("Removing %s", evc)
with evc.lock:
if not evc.archived:
evc.deactivate()
evc.disable()
self.sched.remove(evc)
evc.remove_current_flows(sync=False)
evc.remove_failover_flows(sync=False)
evc.archive()
evc.remove_uni_tags()
evc.sync()
emit_event(
self.controller, "deleted",
content=map_evc_event_content(evc)
)
log.info("EVC removed. %s", evc)
result = {"response": f"Circuit {circuit_id} removed"}
status = 200
log.debug("delete_circuit result %s %s", result, status)
return JSONResponse(result, status_code=status)
@rest("/v2/evc/{circuit_id}/metadata", methods=["GET"])
def get_metadata(self, request: Request) -> JSONResponse:
"""Get metadata from an EVC."""
circuit_id = request.path_params["circuit_id"]
try:
return (
JSONResponse({"metadata": self.circuits[circuit_id].metadata})
)
except KeyError as error:
raise HTTPException(
404,
detail=f"circuit_id {circuit_id} not found."
) from error
@rest("/v2/evc/metadata", methods=["POST"])
@validate_openapi(spec)
def bulk_add_metadata(self, request: Request) -> JSONResponse:
"""Add metadata to a bulk of EVCs."""
data = get_json_or_400(request, self.controller.loop)
circuit_ids = data.pop("circuit_ids")
self.mongo_controller.update_evcs_metadata(circuit_ids, data, "add")
fail_evcs = []
for _id in circuit_ids:
try:
evc = self.circuits[_id]
evc.extend_metadata(data)
except KeyError:
fail_evcs.append(_id)
if fail_evcs:
raise HTTPException(404, detail=fail_evcs)
return JSONResponse("Operation successful", status_code=201)
@rest("/v2/evc/{circuit_id}/metadata", methods=["POST"])
@validate_openapi(spec)
def add_metadata(self, request: Request) -> JSONResponse:
"""Add metadata to an EVC."""
circuit_id = request.path_params["circuit_id"]
metadata = get_json_or_400(request, self.controller.loop)
if not isinstance(metadata, dict):
raise HTTPException(400, f"Invalid metadata value: {metadata}")
try:
evc = self.circuits[circuit_id]
except KeyError as error:
raise HTTPException(
404,
detail=f"circuit_id {circuit_id} not found."
) from error
evc.extend_metadata(metadata)
evc.sync()
return JSONResponse("Operation successful", status_code=201)
@rest("/v2/evc/metadata/{key}", methods=["DELETE"])
@validate_openapi(spec)
def bulk_delete_metadata(self, request: Request) -> JSONResponse:
"""Delete metada from a bulk of EVCs"""
data = get_json_or_400(request, self.controller.loop)
key = request.path_params["key"]
circuit_ids = data.pop("circuit_ids")
self.mongo_controller.update_evcs_metadata(
circuit_ids, {key: ""}, "del"
)
fail_evcs = []
for _id in circuit_ids:
try:
evc = self.circuits[_id]
evc.remove_metadata(key)
except KeyError:
fail_evcs.append(_id)
if fail_evcs:
raise HTTPException(404, detail=fail_evcs)
return JSONResponse("Operation successful")
@rest("/v2/evc/{circuit_id}/metadata/{key}", methods=["DELETE"])
def delete_metadata(self, request: Request) -> JSONResponse:
"""Delete metadata from an EVC."""
circuit_id = request.path_params["circuit_id"]
key = request.path_params["key"]
try:
evc = self.circuits[circuit_id]
except KeyError as error:
raise HTTPException(
404,
detail=f"circuit_id {circuit_id} not found."
) from error
evc.remove_metadata(key)
evc.sync()
return JSONResponse("Operation successful")
@rest("/v2/evc/{circuit_id}/redeploy", methods=["PATCH"])
def redeploy(self, request: Request) -> JSONResponse:
"""Endpoint to force the redeployment of an EVC."""
circuit_id = request.path_params["circuit_id"]
log.debug("redeploy /v2/evc/%s/redeploy", circuit_id)
try:
evc = self.circuits[circuit_id]
except KeyError:
raise HTTPException(
404,
detail=f"circuit_id {circuit_id} not found"
) from KeyError
deployed = False
if evc.is_enabled():
with evc.lock:
evc.remove_current_flows(sync=False)
evc.remove_failover_flows(sync=True)
deployed = evc.deploy()
if deployed:
result = {"response": f"Circuit {circuit_id} redeploy received."}
status = 202
else:
result = {
"response": f"Circuit {circuit_id} is disabled."
}
status = 409
return JSONResponse(result, status_code=status)
@rest("/v2/evc/schedule/", methods=["POST"])
@validate_openapi(spec)
def create_schedule(self, request: Request) -> JSONResponse:
"""
Create a new schedule for a given circuit.
This service do no check if there are conflicts with another schedule.
Payload example:
{
"circuit_id":"aa:bb:cc",
"schedule": {
"date": "2019-08-07T14:52:10.967Z",
"interval": "string",
"frequency": "1 * * * *",
"action": "create"
}
}
"""
log.debug("create_schedule /v2/evc/schedule/")
data = get_json_or_400(request, self.controller.loop)
circuit_id = data["circuit_id"]
schedule_data = data["schedule"]
# Get EVC from circuits buffer
circuits = self._get_circuits_buffer()
# get the circuit
evc = circuits.get(circuit_id)
# get the circuit
if not evc:
result = f"circuit_id {circuit_id} not found"
log.debug("create_schedule result %s %s", result, 404)
raise HTTPException(404, detail=result)
# new schedule from dict
new_schedule = CircuitSchedule.from_dict(schedule_data)
# If there is no schedule, create the list
if not evc.circuit_scheduler:
evc.circuit_scheduler = []
# Add the new schedule
evc.circuit_scheduler.append(new_schedule)
# Add schedule job
self.sched.add_circuit_job(evc, new_schedule)
# save circuit to mongodb
evc.sync()
result = new_schedule.as_dict()
status = 201
log.debug("create_schedule result %s %s", result, status)
return JSONResponse(result, status_code=status)
@rest("/v2/evc/schedule/{schedule_id}", methods=["PATCH"])
@validate_openapi(spec)
def update_schedule(self, request: Request) -> JSONResponse:
"""Update a schedule.
Change all attributes from the given schedule from a EVC circuit.
The schedule ID is preserved as default.
Payload example:
{
"date": "2019-08-07T14:52:10.967Z",
"interval": "string",
"frequency": "1 * * *",
"action": "create"
}
"""
data = get_json_or_400(request, self.controller.loop)
schedule_id = request.path_params["schedule_id"]
log.debug("update_schedule /v2/evc/schedule/%s", schedule_id)
# Try to find a circuit schedule
evc, found_schedule = self._find_evc_by_schedule_id(schedule_id)
# Can not modify circuits deleted and archived
if not found_schedule:
result = f"schedule_id {schedule_id} not found"
log.debug("update_schedule result %s %s", result, 404)
raise HTTPException(404, detail=result)
new_schedule = CircuitSchedule.from_dict(data)
new_schedule.id = found_schedule.id
# Remove the old schedule
evc.circuit_scheduler.remove(found_schedule)
# Append the modified schedule
evc.circuit_scheduler.append(new_schedule)
# Cancel all schedule jobs
self.sched.cancel_job(found_schedule.id)
# Add the new circuit schedule
self.sched.add_circuit_job(evc, new_schedule)
# Save EVC to mongodb
evc.sync()
result = new_schedule.as_dict()
status = 200
log.debug("update_schedule result %s %s", result, status)
return JSONResponse(result, status_code=status)
@rest("/v2/evc/schedule/{schedule_id}", methods=["DELETE"])
def delete_schedule(self, request: Request) -> JSONResponse:
"""Remove a circuit schedule.
Remove the Schedule from EVC.
Remove the Schedule from cron job.
Save the EVC to the Storehouse.
"""
schedule_id = request.path_params["schedule_id"]
log.debug("delete_schedule /v2/evc/schedule/%s", schedule_id)
evc, found_schedule = self._find_evc_by_schedule_id(schedule_id)
# Can not modify circuits deleted and archived
if not found_schedule:
result = f"schedule_id {schedule_id} not found"
log.debug("delete_schedule result %s %s", result, 404)
raise HTTPException(404, detail=result)
# Remove the old schedule
evc.circuit_scheduler.remove(found_schedule)
# Cancel all schedule jobs
self.sched.cancel_job(found_schedule.id)
# Save EVC to mongodb
evc.sync()
result = "Schedule removed"
status = 200
log.debug("delete_schedule result %s %s", result, status)
return JSONResponse(result, status_code=status)
def _check_no_tag_duplication(
self,
evc_id: str,
uni_a: Optional[UNI] = None,
uni_z: Optional[UNI] = None
):
"""Check if the given EVC has UNIs with no tag and if these are
duplicated. Raise DuplicatedNoTagUNI if duplication is found.
Args:
evc (dict): EVC to be analyzed.
"""
# No UNIs
if not (uni_a or uni_z):
return
if (not (uni_a and not uni_a.user_tag) and
not (uni_z and not uni_z.user_tag)):
return
for circuit in self.circuits.copy().values():
if (not circuit.archived and circuit._id != evc_id):
if uni_a and uni_a.user_tag is None:
circuit.check_no_tag_duplicate(uni_a)
if uni_z and uni_z.user_tag is None:
circuit.check_no_tag_duplicate(uni_z)
@listen_to("kytos/topology.link_up")
def on_link_up(self, event):
"""Change circuit when link is up or end_maintenance."""
self.handle_link_up(event)
def handle_link_up(self, event):
"""Change circuit when link is up or end_maintenance."""
log.info("Event handle_link_up %s", event.content["link"])
for evc in self.get_evcs_by_svc_level():
if evc.is_enabled() and not evc.archived:
with evc.lock:
evc.handle_link_up(event.content["link"])
# Possibly replace this with interruptions?
@listen_to(
'.*.switch.interface.(link_up|link_down|created|deleted)'
)
def on_interface_link_change(self, event: KytosEvent):
"""
Handler for interface link_up and link_down events.
"""
self.handle_on_interface_link_change(event)
def handle_on_interface_link_change(self, event: KytosEvent):
"""
Handler to sort interface events {link_(up, down), create, deleted}
To avoid multiple database updated (link flap):
Every interface is identfied and processed in parallel.
Once an interface event is received a time is started.
While time is running self._intf_events will be updated.
After time has passed last received event will be processed.
"""
iface = event.content.get("interface")
with self._lock_interfaces[iface.id]:
_now = event.timestamp
# Return out of order events
if (
iface.id in self._intf_events
and self._intf_events[iface.id]["event"].timestamp > _now
):
return
self._intf_events[iface.id].update({"event": event})
if "last_acquired" in self._intf_events[iface.id]:
return
self._intf_events[iface.id].update({"last_acquired": now()})
time.sleep(settings.UNI_STATE_CHANGE_DELAY)
with self._lock_interfaces[iface.id]:
event = self._intf_events[iface.id]["event"]
self._intf_events[iface.id].pop('last_acquired', None)
_, _, event_type = event.name.rpartition('.')
if event_type in ('link_up', 'created'):
self.handle_interface_link_up(iface)
elif event_type in ('link_down', 'deleted'):
self.handle_interface_link_down(iface)
def handle_interface_link_up(self, interface):
"""
Handler for interface link_up events
"""
log.info("Event handle_interface_link_up %s", interface)
for evc in self.get_evcs_by_svc_level():
with evc.lock:
evc.handle_interface_link_up(
interface
)
def handle_interface_link_down(self, interface):
"""
Handler for interface link_down events
"""
log.info("Event handle_interface_link_down %s", interface)
for evc in self.get_evcs_by_svc_level():
with evc.lock:
evc.handle_interface_link_down(
interface
)
@listen_to("kytos/topology.link_down", pool="dynamic_single")
def on_link_down(self, event):
"""Change circuit when link is down or under_mantenance."""
self.handle_link_down(event)
# pylint: disable=too-many-branches
# pylint: disable=too-many-locals
def handle_link_down(self, event):
"""Change circuit when link is down or under_mantenance."""
link = event.content["link"]
log.info("Event handle_link_down %s", link)
switch_flows = {}
evcs_with_failover = []
evcs_normal = []
check_failover = []
failover_event_contents = {}
for evc in self.get_evcs_by_svc_level():
with evc.lock:
if evc.is_affected_by_link(link):
evc.affected_by_link_at = event.timestamp
# if there is no failover path, handles link down the
# tradditional way
if (
not evc.failover_path or
evc.is_failover_path_affected_by_link(link)
):
evcs_normal.append(evc)
continue
try:
dpid_flows = evc.get_failover_flows()
evc.old_path = evc.current_path
evc.current_path = evc.failover_path
evc.failover_path = Path([])
# pylint: disable=broad-except
except Exception:
err = traceback.format_exc().replace("\n", ", ")
log.error(
"Ignore Failover path for "
f"{evc} due to error: {err}"
)
evcs_normal.append(evc)
continue
for dpid, flows in dpid_flows.items():
switch_flows.setdefault(dpid, [])
switch_flows[dpid].extend(flows)
evcs_with_failover.append(evc)
failover_event_contents[evc.id] = map_evc_event_content(
evc,
flows={k: v.copy() for k, v in switch_flows.items()}
)
elif evc.is_failover_path_affected_by_link(link):
evc.old_path = evc.failover_path
evc.failover_path = Path([])
check_failover.append(evc)
if failover_event_contents:
emit_event(self.controller, "failover_link_down",
content=deepcopy(failover_event_contents))
send_flow_mods_event(self.controller, switch_flows, 'install')
for evc in evcs_normal:
emit_event(
self.controller,
"evc_affected_by_link_down",
content={"link": link} | map_evc_event_content(evc)
)
evcs_to_update = []
for evc in evcs_with_failover:
evcs_to_update.append(evc.as_dict())
log.info(
f"{evc} redeployed with failover due to link down {link.id}"
)
for evc in check_failover:
evcs_to_update.append(evc.as_dict())
self.mongo_controller.update_evcs(evcs_to_update)
emit_event(
self.controller,
"cleanup_evcs_old_path",
content={"evcs": evcs_with_failover + check_failover}
)
@listen_to("kytos/mef_eline.evc_affected_by_link_down")
def on_evc_affected_by_link_down(self, event):
"""Change circuit when link is down or under_mantenance."""
self.handle_evc_affected_by_link_down(event)
def handle_evc_affected_by_link_down(self, event):
"""Change circuit when link is down or under_mantenance."""
evc = self.circuits.get(event.content["evc_id"])
link = event.content['link']
if not evc:
return
with evc.lock:
if not evc.is_affected_by_link(link):
return
result = evc.handle_link_down()
event_name = "error_redeploy_link_down"
if result:
log.info(f"{evc} redeployed due to link down {link.id}")
event_name = "redeployed_link_down"
emit_event(self.controller, event_name,
content=map_evc_event_content(evc))
@listen_to("kytos/mef_eline.(redeployed_link_(up|down)|deployed)")
def on_evc_deployed(self, event):
"""Handle EVC deployed|redeployed_link_down."""
self.handle_evc_deployed(event)
def handle_evc_deployed(self, event):
"""Setup failover path on evc deployed."""
evc = self.circuits.get(event.content["evc_id"])
if not evc:
return
evc.try_setup_failover_path()
@listen_to("kytos/mef_eline.cleanup_evcs_old_path")
def on_cleanup_evcs_old_path(self, event):
"""Handle cleanup evcs old path."""
self.handle_cleanup_evcs_old_path(event)
def handle_cleanup_evcs_old_path(self, event):
"""Handle cleanup evcs old path."""
evcs = event.content.get("evcs", [])
event_contents: dict[str, dict] = defaultdict(list)
total_flows = {}
for evc in evcs:
if not evc.old_path:
continue
with evc.lock:
removed_flows = {}
try:
nni_flows = prepare_delete_flow(
evc._prepare_nni_flows(evc.old_path)
)
uni_flows = prepare_delete_flow(
evc._prepare_uni_flows(evc.old_path, skip_in=True)
)
removed_flows = merge_flow_dicts(
nni_flows, uni_flows
)
# pylint: disable=broad-except
except Exception:
err = traceback.format_exc().replace("\n", ", ")
log.error(f"Fail to remove {evc} old_path: {err}")
continue
if removed_flows:
total_flows = merge_flow_dicts(total_flows, removed_flows)
content = map_evc_event_content(
evc,
removed_flows=deepcopy(removed_flows),
current_path=evc.current_path.as_dict(),
)
event_contents[evc.id] = content
evc.old_path = Path([])
if event_contents:
send_flow_mods_event(self.controller, total_flows, 'delete')
emit_event(self.controller, "failover_old_path",
content=event_contents)
@listen_to("kytos/topology.topology_loaded")
def on_topology_loaded(self, event): # pylint: disable=unused-argument
"""Load EVCs once the topology is available."""
self.load_all_evcs()
def load_all_evcs(self):
"""Try to load all EVCs on startup."""
circuits = self.mongo_controller.get_circuits()['circuits'].items()
for circuit_id, circuit in circuits:
if circuit_id not in self.circuits:
self._load_evc(circuit)
emit_event(self.controller, "evcs_loaded", content=dict(circuits),
timeout=1)
def _load_evc(self, circuit_dict):
"""Load one EVC from mongodb to memory."""
try: