forked from kytos/mef_eline
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathevc.py
1944 lines (1716 loc) · 69.8 KB
/
evc.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
"""Classes used in the main application.""" # pylint: disable=too-many-lines
import traceback
from collections import OrderedDict, defaultdict
from copy import deepcopy
from datetime import datetime
from operator import eq, ne
from threading import Lock
from typing import Union
from uuid import uuid4
import httpx
from glom import glom
from tenacity import (retry, retry_if_exception_type, stop_after_attempt,
wait_combine, wait_fixed, wait_random)
from kytos.core import log
from kytos.core.common import EntityStatus, GenericEntity
from kytos.core.exceptions import KytosNoTagAvailableError, KytosTagError
from kytos.core.helpers import get_time, now
from kytos.core.interface import UNI, Interface, TAGRange
from kytos.core.link import Link
from kytos.core.retry import before_sleep
from kytos.core.tag_ranges import range_difference
from napps.kytos.mef_eline import controllers, settings
from napps.kytos.mef_eline.exceptions import (ActivationError,
DuplicatedNoTagUNI,
EVCPathNotInstalled,
FlowModException, InvalidPath)
from napps.kytos.mef_eline.utils import (check_disabled_component,
compare_endpoint_trace,
compare_uni_out_trace, emit_event,
make_uni_list, map_dl_vlan,
map_evc_event_content,
merge_flow_dicts)
from .path import DynamicPathManager, Path
class EVCBase(GenericEntity):
"""Class to represent a circuit."""
attributes_requiring_redeploy = [
"primary_path",
"backup_path",
"dynamic_backup_path",
"queue_id",
"sb_priority",
"primary_constraints",
"secondary_constraints",
"uni_a",
"uni_z",
]
required_attributes = ["name", "uni_a", "uni_z"]
updatable_attributes = {
"uni_a",
"uni_z",
"name",
"start_date",
"end_date",
"queue_id",
"bandwidth",
"primary_path",
"backup_path",
"dynamic_backup_path",
"primary_constraints",
"secondary_constraints",
"owner",
"sb_priority",
"service_level",
"circuit_scheduler",
"metadata",
"enabled"
}
# pylint: disable=too-many-statements
def __init__(self, controller, **kwargs):
"""Create an EVC instance with the provided parameters.
Args:
id(str): EVC identifier. Whether it's None an ID will be genereted.
Only the first 14 bytes passed will be used.
name: represents an EVC name.(Required)
uni_a (UNI): Endpoint A for User Network Interface.(Required)
uni_z (UNI): Endpoint Z for User Network Interface.(Required)
start_date(datetime|str): Date when the EVC was registred.
Default is now().
end_date(datetime|str): Final date that the EVC will be fineshed.
Default is None.
bandwidth(int): Bandwidth used by EVC instance. Default is 0.
primary_links(list): Primary links used by evc. Default is []
backup_links(list): Backups links used by evc. Default is []
current_path(list): Circuit being used at the moment if this is an
active circuit. Default is [].
failover_path(list): Path being used to provide EVC protection via
failover during link failures. Default is [].
primary_path(list): primary circuit offered to user IF one or more
links were provided. Default is [].
backup_path(list): backup circuit offered to the user IF one or
more links were provided. Default is [].
dynamic_backup_path(bool): Enable computer backup path dynamically.
Dafault is False.
creation_time(datetime|str): datetime when the circuit should be
activated. default is now().
enabled(Boolean): attribute to indicate the administrative state;
default is False.
active(Boolean): attribute to indicate the operational state;
default is False.
archived(Boolean): indicate the EVC has been deleted and is
archived; default is False.
owner(str): The EVC owner. Default is None.
sb_priority(int): Service level provided in the request.
Default is None.
service_level(int): Service level provided. The higher the better.
Default is 0.
Raises:
ValueError: raised when object attributes are invalid.
"""
self._controller = controller
self._validate(**kwargs)
super().__init__()
# required attributes
self._id = kwargs.get("id", uuid4().hex)[:14]
self.uni_a: UNI = kwargs.get("uni_a")
self.uni_z: UNI = kwargs.get("uni_z")
self.name = kwargs.get("name")
# optional attributes
self.start_date = get_time(kwargs.get("start_date")) or now()
self.end_date = get_time(kwargs.get("end_date")) or None
self.queue_id = kwargs.get("queue_id", -1)
self.bandwidth = kwargs.get("bandwidth", 0)
self.primary_links = Path(kwargs.get("primary_links", []))
self.backup_links = Path(kwargs.get("backup_links", []))
self.current_path = Path(kwargs.get("current_path", []))
self.failover_path = Path(kwargs.get("failover_path", []))
self.primary_path = Path(kwargs.get("primary_path", []))
self.backup_path = Path(kwargs.get("backup_path", []))
self.dynamic_backup_path = kwargs.get("dynamic_backup_path", False)
self.primary_constraints = kwargs.get("primary_constraints", {})
self.secondary_constraints = kwargs.get("secondary_constraints", {})
self.creation_time = get_time(kwargs.get("creation_time")) or now()
self.owner = kwargs.get("owner", None)
self.sb_priority = kwargs.get("sb_priority", None) or kwargs.get(
"priority", None
)
self.service_level = kwargs.get("service_level", 0)
self.circuit_scheduler = kwargs.get("circuit_scheduler", [])
self.flow_removed_at = get_time(kwargs.get("flow_removed_at")) or None
self.updated_at = get_time(kwargs.get("updated_at")) or now()
self.execution_rounds = kwargs.get("execution_rounds", 0)
self.current_links_cache = set()
self.primary_links_cache = set()
self.backup_links_cache = set()
self.affected_by_link_at = get_time("0001-01-01T00:00:00")
self.old_path = Path([])
self.lock = Lock()
self.archived = kwargs.get("archived", False)
self.metadata = kwargs.get("metadata", {})
self._mongo_controller = controllers.ELineController()
if kwargs.get("active", False):
self.activate()
else:
self.deactivate()
if kwargs.get("enabled", False):
self.enable()
else:
self.disable()
# datetime of user request for a EVC (or datetime when object was
# created)
self.request_time = kwargs.get("request_time", now())
# dict with the user original request (input)
self._requested = kwargs
# Special cases: No tag, any, untagged
self.special_cases = {None, "4096/4096", 0}
self.table_group = kwargs.get("table_group")
def sync(self, keys: set = None):
"""Sync this EVC in the MongoDB."""
self.updated_at = now()
if keys:
self._mongo_controller.update_evc(self.as_dict(keys))
return
self._mongo_controller.upsert_evc(self.as_dict())
def _get_unis_use_tags(self, **kwargs) -> tuple[UNI, UNI]:
"""Obtain both UNIs (uni_a, uni_z).
If a UNI is changing, verify tags"""
uni_a = kwargs.get("uni_a", None)
uni_a_flag = False
if uni_a and uni_a != self.uni_a:
uni_a_flag = True
self._use_uni_vlan(uni_a, uni_dif=self.uni_a)
uni_z = kwargs.get("uni_z", None)
if uni_z and uni_z != self.uni_z:
try:
self._use_uni_vlan(uni_z, uni_dif=self.uni_z)
self.make_uni_vlan_available(self.uni_z, uni_dif=uni_z)
except KytosTagError as err:
if uni_a_flag:
self.make_uni_vlan_available(uni_a, uni_dif=self.uni_a)
raise err
else:
uni_z = self.uni_z
if uni_a_flag:
self.make_uni_vlan_available(self.uni_a, uni_dif=uni_a)
else:
uni_a = self.uni_a
return uni_a, uni_z
def update(self, **kwargs):
"""Update evc attributes.
This method will raises an error trying to change the following
attributes: [creation_time, active, current_path, failover_path,
_id, archived]
[name, uni_a and uni_z]
Returns:
the values for enable and a redeploy attribute, if exists and None
otherwise
Raises:
ValueError: message with error detail.
"""
enable, redeploy = (None, None)
if not self._tag_lists_equal(**kwargs):
raise ValueError(
"UNI_A and UNI_Z tag lists should be the same."
)
uni_a, uni_z = self._get_unis_use_tags(**kwargs)
check_disabled_component(uni_a, uni_z)
self._validate_has_primary_or_dynamic(
primary_path=kwargs.get("primary_path"),
dynamic_backup_path=kwargs.get("dynamic_backup_path"),
uni_a=uni_a,
uni_z=uni_z,
)
for attribute, value in kwargs.items():
if attribute not in self.updatable_attributes:
raise ValueError(f"{attribute} can't be updated.")
if attribute in ("primary_path", "backup_path"):
try:
value.is_valid(
uni_a.interface.switch, uni_z.interface.switch
)
except InvalidPath as exception:
raise ValueError( # pylint: disable=raise-missing-from
f"{attribute} is not a " f"valid path: {exception}"
)
for attribute, value in kwargs.items():
if attribute == "enabled":
if value:
self.enable()
else:
self.disable()
enable = value
else:
setattr(self, attribute, value)
if attribute in self.attributes_requiring_redeploy:
redeploy = True
self.sync(set(kwargs.keys()))
return enable, redeploy
def set_flow_removed_at(self):
"""Update flow_removed_at attribute."""
self.flow_removed_at = now()
def has_recent_removed_flow(self, setting=settings):
"""Check if any flow has been removed from the evc"""
if self.flow_removed_at is None:
return False
res_seconds = (now() - self.flow_removed_at).seconds
return res_seconds < setting.TIME_RECENT_DELETED_FLOWS
def is_recent_updated(self, setting=settings):
"""Check if the evc has been updated recently"""
res_seconds = (now() - self.updated_at).seconds
return res_seconds < setting.TIME_RECENT_UPDATED
def __repr__(self):
"""Repr method."""
return f"EVC({self._id}, {self.name})"
def _validate(self, **kwargs):
"""Do Basic validations.
Verify required attributes: name, uni_a, uni_z
Raises:
ValueError: message with error detail.
"""
for attribute in self.required_attributes:
if attribute not in kwargs:
raise ValueError(f"{attribute} is required.")
if "uni" in attribute:
uni = kwargs.get(attribute)
if not isinstance(uni, UNI):
raise ValueError(f"{attribute} is an invalid UNI.")
def _tag_lists_equal(self, **kwargs):
"""Verify that tag lists are the same."""
uni_a = kwargs.get("uni_a") or self.uni_a
uni_z = kwargs.get("uni_z") or self.uni_z
uni_a_list = uni_z_list = False
if (uni_a.user_tag and isinstance(uni_a.user_tag, TAGRange)):
uni_a_list = True
if (uni_z.user_tag and isinstance(uni_z.user_tag, TAGRange)):
uni_z_list = True
if uni_a_list and uni_z_list:
return uni_a.user_tag.value == uni_z.user_tag.value
return uni_a_list == uni_z_list
def _validate_has_primary_or_dynamic(
self,
primary_path=None,
dynamic_backup_path=None,
uni_a=None,
uni_z=None,
) -> None:
"""Validate that it must have a primary path or allow dynamic paths."""
primary_path = (
primary_path
if primary_path is not None
else self.primary_path
)
dynamic_backup_path = (
dynamic_backup_path
if dynamic_backup_path is not None
else self.dynamic_backup_path
)
uni_a = uni_a if uni_a is not None else self.uni_a
uni_z = uni_z if uni_z is not None else self.uni_z
if (
not primary_path
and not dynamic_backup_path
and uni_a and uni_z
and uni_a.interface.switch != uni_z.interface.switch
):
msg = "The EVC must have a primary path or allow dynamic paths."
raise ValueError(msg)
def __eq__(self, other):
"""Override the default implementation."""
if not isinstance(other, EVC):
return False
attrs_to_compare = ["name", "uni_a", "uni_z", "owner", "bandwidth"]
for attribute in attrs_to_compare:
if getattr(other, attribute) != getattr(self, attribute):
return False
return True
def is_intra_switch(self):
"""Check if the UNIs are in the same switch."""
return self.uni_a.interface.switch == self.uni_z.interface.switch
def check_no_tag_duplicate(self, other_uni: UNI):
"""Check if a no tag UNI is duplicated."""
if other_uni in (self.uni_a, self.uni_z):
msg = f"UNI with interface {other_uni.interface.id} is"\
f" duplicated with {self}."
raise DuplicatedNoTagUNI(msg)
def as_dict(self, keys: set = None):
"""Return a dictionary representing an EVC object.
keys: Only fields on this variable will be
returned in the dictionary"""
evc_dict = {
"id": self.id,
"name": self.name,
"uni_a": self.uni_a.as_dict(),
"uni_z": self.uni_z.as_dict(),
}
time_fmt = "%Y-%m-%dT%H:%M:%S"
evc_dict["start_date"] = self.start_date
if isinstance(self.start_date, datetime):
evc_dict["start_date"] = self.start_date.strftime(time_fmt)
evc_dict["end_date"] = self.end_date
if isinstance(self.end_date, datetime):
evc_dict["end_date"] = self.end_date.strftime(time_fmt)
evc_dict["queue_id"] = self.queue_id
evc_dict["bandwidth"] = self.bandwidth
evc_dict["primary_links"] = self.primary_links.as_dict()
evc_dict["backup_links"] = self.backup_links.as_dict()
evc_dict["current_path"] = self.current_path.as_dict()
evc_dict["failover_path"] = self.failover_path.as_dict()
evc_dict["primary_path"] = self.primary_path.as_dict()
evc_dict["backup_path"] = self.backup_path.as_dict()
evc_dict["dynamic_backup_path"] = self.dynamic_backup_path
evc_dict["metadata"] = self.metadata
evc_dict["request_time"] = self.request_time
if isinstance(self.request_time, datetime):
evc_dict["request_time"] = self.request_time.strftime(time_fmt)
time = self.creation_time.strftime(time_fmt)
evc_dict["creation_time"] = time
evc_dict["owner"] = self.owner
evc_dict["circuit_scheduler"] = [
sc.as_dict() for sc in self.circuit_scheduler
]
evc_dict["active"] = self.is_active()
evc_dict["enabled"] = self.is_enabled()
evc_dict["archived"] = self.archived
evc_dict["sb_priority"] = self.sb_priority
evc_dict["service_level"] = self.service_level
evc_dict["primary_constraints"] = self.primary_constraints
evc_dict["secondary_constraints"] = self.secondary_constraints
evc_dict["flow_removed_at"] = self.flow_removed_at
evc_dict["updated_at"] = self.updated_at
if keys:
selected = {}
for key in keys:
selected[key] = evc_dict[key]
selected["id"] = evc_dict["id"]
return selected
return evc_dict
@property
def id(self): # pylint: disable=invalid-name
"""Return this EVC's ID."""
return self._id
def archive(self):
"""Archive this EVC on deletion."""
self.archived = True
def _use_uni_vlan(
self,
uni: UNI,
uni_dif: Union[None, UNI] = None
):
"""Use tags from UNI"""
if uni.user_tag is None:
return
tag = uni.user_tag.value
tag_type = uni.user_tag.tag_type
if (uni_dif and isinstance(tag, list) and
isinstance(uni_dif.user_tag.value, list)):
tag = range_difference(tag, uni_dif.user_tag.value)
if not tag:
return
uni.interface.use_tags(
self._controller, tag, tag_type, use_lock=True, check_order=False
)
def make_uni_vlan_available(
self,
uni: UNI,
uni_dif: Union[None, UNI] = None,
):
"""Make available tag from UNI"""
if uni.user_tag is None:
return
tag = uni.user_tag.value
tag_type = uni.user_tag.tag_type
if (uni_dif and isinstance(tag, list) and
isinstance(uni_dif.user_tag.value, list)):
tag = range_difference(tag, uni_dif.user_tag.value)
if not tag:
return
try:
conflict = uni.interface.make_tags_available(
self._controller, tag, tag_type, use_lock=True,
check_order=False
)
except KytosTagError as err:
log.error(f"Error in {self}: {err}")
return
if conflict:
intf = uni.interface.id
log.warning(f"Tags {conflict} was already available in {intf}")
def remove_uni_tags(self):
"""Remove both UNI usage of a tag"""
self.make_uni_vlan_available(self.uni_a)
self.make_uni_vlan_available(self.uni_z)
# pylint: disable=fixme, too-many-public-methods
class EVCDeploy(EVCBase):
"""Class to handle the deploy procedures."""
def create(self):
"""Create a EVC."""
def discover_new_paths(self):
"""Discover new paths to satisfy this circuit and deploy it."""
return DynamicPathManager.get_best_paths(self,
**self.primary_constraints)
def get_failover_path_candidates(self):
"""Get failover paths to satisfy this EVC."""
# in the future we can return primary/backup paths as well
# we just have to properly handle link_up and failover paths
# if (
# self.is_using_primary_path() and
# self.backup_path.status is EntityStatus.UP
# ):
# yield self.backup_path
return DynamicPathManager.get_disjoint_paths(self, self.current_path)
def change_path(self):
"""Change EVC path."""
def reprovision(self):
"""Force the EVC (re-)provisioning."""
def is_affected_by_link(self, link):
"""Return True if this EVC has the given link on its current path."""
return link in self.current_path
def link_affected_by_interface(self, interface):
"""Return True if this EVC has the given link on its current path."""
return self.current_path.link_affected_by_interface(interface)
def is_backup_path_affected_by_link(self, link):
"""Return True if the backup path of this EVC uses the given link."""
return link in self.backup_path
# pylint: disable=invalid-name
def is_primary_path_affected_by_link(self, link):
"""Return True if the primary path of this EVC uses the given link."""
return link in self.primary_path
def is_failover_path_affected_by_link(self, link):
"""Return True if this EVC has the given link on its failover path."""
return link in self.failover_path
def is_eligible_for_failover_path(self):
"""Verify if this EVC is eligible for failover path (EP029)"""
# In the future this function can be augmented to consider
# primary/backup, primary/dynamic, and other path combinations
return (
self.dynamic_backup_path and
not self.primary_path and not self.backup_path
)
def is_using_primary_path(self):
"""Verify if the current deployed path is self.primary_path."""
return self.primary_path and (self.current_path == self.primary_path)
def is_using_backup_path(self):
"""Verify if the current deployed path is self.backup_path."""
return self.backup_path and (self.current_path == self.backup_path)
def is_using_dynamic_path(self):
"""Verify if the current deployed path is a dynamic path."""
if (
self.current_path
and not self.is_using_primary_path()
and not self.is_using_backup_path()
and self.current_path.status == EntityStatus.UP
):
return True
return False
def deploy_to_backup_path(self, old_path_dict: dict = None):
"""Deploy the backup path into the datapaths of this circuit.
If the backup_path attribute is valid and up, this method will try to
deploy this backup_path.
If everything fails and dynamic_backup_path is True, then tries to
deploy a dynamic path.
"""
# TODO: Remove flows from current (cookies)
if self.is_using_backup_path():
# TODO: Log to say that cannot move backup to backup
return True
success = False
if self.backup_path.status is EntityStatus.UP:
success = self.deploy_to_path(self.backup_path, old_path_dict)
if success:
return True
if self.dynamic_backup_path or self.is_intra_switch():
return self.deploy_to_path(old_path_dict=old_path_dict)
return False
def deploy_to_primary_path(self, old_path_dict: dict = None):
"""Deploy the primary path into the datapaths of this circuit.
If the primary_path attribute is valid and up, this method will try to
deploy this primary_path.
"""
# TODO: Remove flows from current (cookies)
if self.is_using_primary_path():
# TODO: Log to say that cannot move primary to primary
return True
if self.primary_path.status is EntityStatus.UP:
return self.deploy_to_path(self.primary_path, old_path_dict)
return False
def deploy(self, old_path_dict: dict = None):
"""Deploy EVC to best path.
Best path can be the primary path, if available. If not, the backup
path, and, if it is also not available, a dynamic path.
"""
if self.archived:
return False
self.enable()
success = self.deploy_to_primary_path(old_path_dict)
if not success:
success = self.deploy_to_backup_path(old_path_dict)
if success:
emit_event(self._controller, "deployed",
content=map_evc_event_content(self))
return success
@staticmethod
def get_path_status(path):
"""Check for the current status of a path.
If any link in this path is down, the path is considered down.
"""
if not path:
return EntityStatus.DISABLED
for link in path:
if link.status is not EntityStatus.UP:
return link.status
return EntityStatus.UP
# def discover_new_path(self):
# # TODO: discover a new path to satisfy this circuit and deploy
def remove(self):
"""Remove EVC path and disable it."""
self.remove_current_flows(sync=False)
self.remove_failover_flows(sync=False)
self.disable()
self.sync()
emit_event(self._controller, "undeployed",
content=map_evc_event_content(self))
def remove_failover_flows(self, exclude_uni_switches=True,
force=True, sync=True) -> None:
"""Remove failover_flows.
By default, it'll exclude UNI switches, if mef_eline has already
called remove_current_flows before then this minimizes the number
of FlowMods and IO.
"""
if not self.failover_path:
return
switches, cookie, excluded = set(), self.get_cookie(), set()
if exclude_uni_switches:
excluded.add(self.uni_a.interface.switch.id)
excluded.add(self.uni_z.interface.switch.id)
for link in self.failover_path:
if link.endpoint_a.switch.id not in excluded:
switches.add(link.endpoint_a.switch.id)
if link.endpoint_b.switch.id not in excluded:
switches.add(link.endpoint_b.switch.id)
flow_mods = {
"switches": list(switches),
"flows": [{
"cookie": cookie,
"cookie_mask": int(0xffffffffffffffff),
"owner": "mef_eline",
}]
}
try:
self._send_flow_mods(
flow_mods,
"delete",
force=force,
)
except FlowModException as err:
log.error(f"Error deleting {self} failover_path flows, {err}")
try:
self.failover_path.make_vlans_available(self._controller)
except KytosTagError as err:
log.error(f"Error removing {self} failover_path: {err}")
self.failover_path = Path([])
if sync:
self.sync()
def remove_current_flows(
self,
current_path=None,
force=True,
sync=True,
return_path=False
) -> dict[str, int]:
"""Remove all flows from current path or path intended for
current path if exists."""
switches, old_path_dict = set(), {}
current_path = self.current_path if not current_path else current_path
if not current_path and not self.is_intra_switch():
return {}
if return_path:
for link in self.current_path:
s_vlan = link.metadata.get("s_vlan")
if s_vlan:
old_path_dict[link.id] = s_vlan.value
for link in current_path:
switches.add(link.endpoint_a.switch.id)
switches.add(link.endpoint_b.switch.id)
switches.add(self.uni_a.interface.switch.id)
switches.add(self.uni_z.interface.switch.id)
flow_mods = {
"switches": list(switches),
"flows": [{
"cookie": self.get_cookie(),
"cookie_mask": int(0xffffffffffffffff),
"owner": "mef_eline",
}]
}
try:
self._send_flow_mods(flow_mods, "delete", force=force)
except FlowModException as err:
log.error(f"Error deleting {self} current_path flows, {err}")
try:
current_path.make_vlans_available(self._controller)
except KytosTagError as err:
log.error(f"Error removing {self} current_path: {err}")
self.current_path = Path([])
self.deactivate()
if sync:
self.sync()
return old_path_dict
def remove_path_flows(
self, path=None, force=True
) -> dict[str, list[dict]]:
"""Remove all flows from path, and return the removed flows."""
dpid_flows_match: dict[str, dict] = defaultdict(lambda: {"flows": []})
out_flows: dict[str, list[dict]] = defaultdict(list)
if not path:
return dpid_flows_match
try:
nni_flows = self._prepare_nni_flows(path)
# pylint: disable=broad-except
except Exception:
err = traceback.format_exc().replace("\n", ", ")
log.error(f"Fail to remove NNI failover flows for {self}: {err}")
nni_flows = {}
for dpid, flows in nni_flows.items():
for flow in flows:
flow_mod = {
"cookie": flow["cookie"],
"match": flow["match"],
"owner": "mef_eline",
"cookie_mask": int(0xffffffffffffffff)
}
dpid_flows_match[dpid]["flows"].append(flow_mod)
out_flows[dpid].append(flow_mod)
try:
uni_flows = self._prepare_uni_flows(path, skip_in=True)
# pylint: disable=broad-except
except Exception:
err = traceback.format_exc().replace("\n", ", ")
log.error(f"Fail to remove UNI failover flows for {self}: {err}")
uni_flows = {}
for dpid, flows in uni_flows.items():
for flow in flows:
flow_mod = {
"cookie": flow["cookie"],
"match": flow["match"],
"owner": "mef_eline",
"cookie_mask": int(0xffffffffffffffff)
}
dpid_flows_match[dpid]["flows"].append(flow_mod)
out_flows[dpid].append(flow_mod)
try:
self._send_flow_mods(
dpid_flows_match, 'delete', force=force, by_switch=True
)
except FlowModException as err:
log.error(
f"Error deleting {self} path flows, path:{path}, error={err}"
)
try:
path.make_vlans_available(self._controller)
except KytosTagError as err:
log.error(f"Error removing {self} path: {err}")
return out_flows
@staticmethod
def links_zipped(path=None):
"""Return an iterator which yields pairs of links in order."""
if not path:
return []
return zip(path[:-1], path[1:])
def should_deploy(self, path=None):
"""Verify if the circuit should be deployed."""
if not path:
log.debug("Path is empty.")
return False
if not self.is_enabled():
log.debug(f"{self} is disabled.")
return False
if not self.is_active():
log.debug(f"{self} will be deployed.")
return True
return False
@staticmethod
def is_uni_interface_active(
*interfaces: Interface
) -> tuple[bool, dict]:
"""Whether UNIs are active and their status & status_reason."""
active = True
bad_interfaces = [
interface
for interface in interfaces
if interface.status != EntityStatus.UP
]
if bad_interfaces:
active = False
interfaces = bad_interfaces
return active, {
interface.id: {
'status': interface.status.value,
'status_reason': interface.status_reason,
}
for interface in interfaces
}
def try_to_activate(self) -> bool:
"""Try to activate the EVC."""
if self.is_intra_switch():
return self._try_to_activate_intra_evc()
return self._try_to_activate_inter_evc()
def _try_to_activate_intra_evc(self) -> bool:
"""Try to activate intra EVC."""
intf_a, intf_z = self.uni_a.interface, self.uni_z.interface
is_active, reason = self.is_uni_interface_active(intf_a, intf_z)
if not is_active:
raise ActivationError(
f"Won't be able to activate {self} due to UNIs: {reason}"
)
self.activate()
return True
def _try_to_activate_inter_evc(self) -> bool:
"""Try to activate inter EVC."""
intf_a, intf_z = self.uni_a.interface, self.uni_z.interface
is_active, reason = self.is_uni_interface_active(intf_a, intf_z)
if not is_active:
raise ActivationError(
f"Won't be able to activate {self} due to UNIs: {reason}"
)
if self.current_path.status != EntityStatus.UP:
raise ActivationError(
f"Won't be able to activate {self} due to current_path "
f"status {self.current_path.status}"
)
self.activate()
return True
# pylint: disable=too-many-branches, too-many-statements
def deploy_to_path(self, path=None, old_path_dict: dict = None):
"""Install the flows for this circuit.
Procedures to deploy:
0. Remove current flows installed
1. Decide if will deploy "path" or discover a new path
2. Choose vlan
3. Install NNI flows
4. Install UNI flows
5. Activate
6. Update current_path
7. Update links caches(primary, current, backup)
"""
self.remove_current_flows(sync=False)
use_path = path or Path([])
if not old_path_dict:
old_path_dict = {}
tag_errors = []
if self.should_deploy(use_path):
try:
use_path.choose_vlans(self._controller, old_path_dict)
except KytosNoTagAvailableError as e:
tag_errors.append(str(e))
use_path = None
else:
for use_path in self.discover_new_paths():
if use_path is None:
continue
try:
use_path.choose_vlans(self._controller, old_path_dict)
break
except KytosNoTagAvailableError as e:
tag_errors.append(str(e))
else:
use_path = None
try:
if use_path:
self._install_flows(use_path)
elif self.is_intra_switch():
use_path = Path()
self._install_direct_uni_flows()
else:
msg = f"{self} was not deployed. No available path was found."
if tag_errors:
msg = self.add_tag_errors(msg, tag_errors)
log.error(msg)
else:
log.warning(msg)
return False
except EVCPathNotInstalled as err:
log.error(
f"Error deploying EVC {self} when calling flow_manager: {err}"
)
self.remove_current_flows(use_path, sync=True)
return False
self.current_path = use_path
msg = f"{self} was deployed."
try:
self.try_to_activate()
except ActivationError as exc:
msg = f"{msg} {str(exc)}"
self.sync()
log.info(msg)
return True
def try_setup_failover_path(
self,
wait=settings.DEPLOY_EVCS_INTERVAL,
warn_if_not_path=True
):
"""Try setup failover_path whenever possible."""
if (
self.failover_path or not self.current_path
or not self.is_active()
):
return
if (now() - self.affected_by_link_at).seconds >= wait:
with self.lock:
self.setup_failover_path(warn_if_not_path)
# pylint: disable=too-many-statements
def setup_failover_path(self, warn_if_not_path=True):
"""Install flows for the failover path of this EVC.
Procedures to deploy:
0. Remove flows currently installed for failover_path (if any)
1. Discover a disjoint path from current_path
2. Choose vlans
3. Install NNI flows
4. Install UNI egress flows
5. Update failover_path
"""
# Intra-switch EVCs have no failover_path