Total Complexity | 348 |
Total Lines | 1914 |
Duplicated Lines | 1.25 % |
Coverage | 93.34% |
Changes | 0 |
Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like build.models.evc often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
1 | """Classes used in the main application.""" # pylint: disable=too-many-lines |
||
2 | 1 | import traceback |
|
3 | 1 | from collections import OrderedDict, defaultdict |
|
4 | 1 | from copy import deepcopy |
|
5 | 1 | from datetime import datetime |
|
6 | 1 | from operator import eq, ne |
|
7 | 1 | from threading import Lock |
|
8 | 1 | from typing import Union |
|
9 | 1 | from uuid import uuid4 |
|
10 | |||
11 | 1 | import httpx |
|
12 | 1 | from glom import glom |
|
13 | 1 | from tenacity import (retry, retry_if_exception_type, stop_after_attempt, |
|
14 | wait_combine, wait_fixed, wait_random) |
||
15 | |||
16 | 1 | from kytos.core import log |
|
17 | 1 | from kytos.core.common import EntityStatus, GenericEntity |
|
18 | 1 | from kytos.core.exceptions import KytosNoTagAvailableError, KytosTagError |
|
19 | 1 | from kytos.core.helpers import get_time, now |
|
20 | 1 | from kytos.core.interface import UNI, Interface, TAGRange |
|
21 | 1 | from kytos.core.link import Link |
|
22 | 1 | from kytos.core.retry import before_sleep |
|
23 | 1 | from kytos.core.tag_ranges import range_difference |
|
24 | 1 | from napps.kytos.mef_eline import controllers, settings |
|
25 | 1 | from napps.kytos.mef_eline.exceptions import (ActivationError, |
|
26 | DuplicatedNoTagUNI, |
||
27 | EVCPathNotInstalled, |
||
28 | FlowModException, InvalidPath) |
||
29 | 1 | from napps.kytos.mef_eline.utils import (check_disabled_component, |
|
30 | compare_endpoint_trace, |
||
31 | compare_uni_out_trace, emit_event, |
||
32 | make_uni_list, map_dl_vlan, |
||
33 | map_evc_event_content, |
||
34 | merge_flow_dicts) |
||
35 | |||
36 | 1 | from .path import DynamicPathManager, Path |
|
37 | |||
38 | |||
39 | 1 | class EVCBase(GenericEntity): |
|
40 | """Class to represent a circuit.""" |
||
41 | |||
42 | 1 | attributes_requiring_redeploy = [ |
|
43 | "primary_path", |
||
44 | "backup_path", |
||
45 | "dynamic_backup_path", |
||
46 | "queue_id", |
||
47 | "sb_priority", |
||
48 | "primary_constraints", |
||
49 | "secondary_constraints", |
||
50 | "uni_a", |
||
51 | "uni_z", |
||
52 | ] |
||
53 | 1 | required_attributes = ["name", "uni_a", "uni_z"] |
|
54 | |||
55 | 1 | updatable_attributes = { |
|
56 | "uni_a", |
||
57 | "uni_z", |
||
58 | "name", |
||
59 | "start_date", |
||
60 | "end_date", |
||
61 | "queue_id", |
||
62 | "bandwidth", |
||
63 | "primary_path", |
||
64 | "backup_path", |
||
65 | "dynamic_backup_path", |
||
66 | "primary_constraints", |
||
67 | "secondary_constraints", |
||
68 | "owner", |
||
69 | "sb_priority", |
||
70 | "service_level", |
||
71 | "circuit_scheduler", |
||
72 | "metadata", |
||
73 | "enabled" |
||
74 | } |
||
75 | |||
76 | # pylint: disable=too-many-statements |
||
77 | 1 | def __init__(self, controller, **kwargs): |
|
78 | """Create an EVC instance with the provided parameters. |
||
79 | |||
80 | Args: |
||
81 | id(str): EVC identifier. Whether it's None an ID will be genereted. |
||
82 | Only the first 14 bytes passed will be used. |
||
83 | name: represents an EVC name.(Required) |
||
84 | uni_a (UNI): Endpoint A for User Network Interface.(Required) |
||
85 | uni_z (UNI): Endpoint Z for User Network Interface.(Required) |
||
86 | start_date(datetime|str): Date when the EVC was registred. |
||
87 | Default is now(). |
||
88 | end_date(datetime|str): Final date that the EVC will be fineshed. |
||
89 | Default is None. |
||
90 | bandwidth(int): Bandwidth used by EVC instance. Default is 0. |
||
91 | primary_links(list): Primary links used by evc. Default is [] |
||
92 | backup_links(list): Backups links used by evc. Default is [] |
||
93 | current_path(list): Circuit being used at the moment if this is an |
||
94 | active circuit. Default is []. |
||
95 | failover_path(list): Path being used to provide EVC protection via |
||
96 | failover during link failures. Default is []. |
||
97 | primary_path(list): primary circuit offered to user IF one or more |
||
98 | links were provided. Default is []. |
||
99 | backup_path(list): backup circuit offered to the user IF one or |
||
100 | more links were provided. Default is []. |
||
101 | dynamic_backup_path(bool): Enable computer backup path dynamically. |
||
102 | Dafault is False. |
||
103 | creation_time(datetime|str): datetime when the circuit should be |
||
104 | activated. default is now(). |
||
105 | enabled(Boolean): attribute to indicate the administrative state; |
||
106 | default is False. |
||
107 | active(Boolean): attribute to indicate the operational state; |
||
108 | default is False. |
||
109 | archived(Boolean): indicate the EVC has been deleted and is |
||
110 | archived; default is False. |
||
111 | owner(str): The EVC owner. Default is None. |
||
112 | sb_priority(int): Service level provided in the request. |
||
113 | Default is None. |
||
114 | service_level(int): Service level provided. The higher the better. |
||
115 | Default is 0. |
||
116 | |||
117 | Raises: |
||
118 | ValueError: raised when object attributes are invalid. |
||
119 | |||
120 | """ |
||
121 | 1 | self._controller = controller |
|
122 | 1 | self._validate(**kwargs) |
|
123 | 1 | super().__init__() |
|
124 | |||
125 | # required attributes |
||
126 | 1 | self._id = kwargs.get("id", uuid4().hex)[:14] |
|
127 | 1 | self.uni_a: UNI = kwargs.get("uni_a") |
|
128 | 1 | self.uni_z: UNI = kwargs.get("uni_z") |
|
129 | 1 | self.name = kwargs.get("name") |
|
130 | |||
131 | # optional attributes |
||
132 | 1 | self.start_date = get_time(kwargs.get("start_date")) or now() |
|
133 | 1 | self.end_date = get_time(kwargs.get("end_date")) or None |
|
134 | 1 | self.queue_id = kwargs.get("queue_id", -1) |
|
135 | |||
136 | 1 | self.bandwidth = kwargs.get("bandwidth", 0) |
|
137 | 1 | self.primary_links = Path(kwargs.get("primary_links", [])) |
|
138 | 1 | self.backup_links = Path(kwargs.get("backup_links", [])) |
|
139 | 1 | self.current_path = Path(kwargs.get("current_path", [])) |
|
140 | 1 | self.failover_path = Path(kwargs.get("failover_path", [])) |
|
141 | 1 | self.primary_path = Path(kwargs.get("primary_path", [])) |
|
142 | 1 | self.backup_path = Path(kwargs.get("backup_path", [])) |
|
143 | 1 | self.dynamic_backup_path = kwargs.get("dynamic_backup_path", False) |
|
144 | 1 | self.primary_constraints = kwargs.get("primary_constraints", {}) |
|
145 | 1 | self.secondary_constraints = kwargs.get("secondary_constraints", {}) |
|
146 | 1 | self.creation_time = get_time(kwargs.get("creation_time")) or now() |
|
147 | 1 | self.owner = kwargs.get("owner", None) |
|
148 | 1 | self.sb_priority = kwargs.get("sb_priority", None) or kwargs.get( |
|
149 | "priority", None |
||
150 | ) |
||
151 | 1 | self.service_level = kwargs.get("service_level", 0) |
|
152 | 1 | self.circuit_scheduler = kwargs.get("circuit_scheduler", []) |
|
153 | 1 | self.flow_removed_at = get_time(kwargs.get("flow_removed_at")) or None |
|
154 | 1 | self.updated_at = get_time(kwargs.get("updated_at")) or now() |
|
155 | 1 | self.execution_rounds = kwargs.get("execution_rounds", 0) |
|
156 | 1 | self.current_links_cache = set() |
|
157 | 1 | self.primary_links_cache = set() |
|
158 | 1 | self.backup_links_cache = set() |
|
159 | 1 | self.affected_by_link_at = get_time("0001-01-01T00:00:00") |
|
160 | 1 | self.old_path = Path([]) |
|
161 | |||
162 | 1 | self.lock = Lock() |
|
163 | |||
164 | 1 | self.archived = kwargs.get("archived", False) |
|
165 | |||
166 | 1 | self.metadata = kwargs.get("metadata", {}) |
|
167 | |||
168 | 1 | self._mongo_controller = controllers.ELineController() |
|
169 | |||
170 | 1 | if kwargs.get("active", False): |
|
171 | 1 | self.activate() |
|
172 | else: |
||
173 | 1 | self.deactivate() |
|
174 | |||
175 | 1 | if kwargs.get("enabled", False): |
|
176 | 1 | self.enable() |
|
177 | else: |
||
178 | 1 | self.disable() |
|
179 | |||
180 | # datetime of user request for a EVC (or datetime when object was |
||
181 | # created) |
||
182 | 1 | self.request_time = kwargs.get("request_time", now()) |
|
183 | # dict with the user original request (input) |
||
184 | 1 | self._requested = kwargs |
|
185 | |||
186 | # Special cases: No tag, any, untagged |
||
187 | 1 | self.special_cases = {None, "4096/4096", 0} |
|
188 | 1 | self.table_group = kwargs.get("table_group") |
|
189 | |||
190 | 1 | def sync(self, keys: set = None): |
|
191 | """Sync this EVC in the MongoDB.""" |
||
192 | 1 | self.updated_at = now() |
|
193 | 1 | if keys: |
|
194 | 1 | self._mongo_controller.update_evc(self.as_dict(keys)) |
|
195 | 1 | return |
|
196 | 1 | self._mongo_controller.upsert_evc(self.as_dict()) |
|
197 | |||
198 | 1 | def _get_unis_use_tags(self, **kwargs) -> tuple[UNI, UNI]: |
|
199 | """Obtain both UNIs (uni_a, uni_z). |
||
200 | If a UNI is changing, verify tags""" |
||
201 | 1 | uni_a = kwargs.get("uni_a", None) |
|
202 | 1 | uni_a_flag = False |
|
203 | 1 | if uni_a and uni_a != self.uni_a: |
|
204 | 1 | uni_a_flag = True |
|
205 | 1 | self._use_uni_vlan(uni_a, uni_dif=self.uni_a) |
|
206 | |||
207 | 1 | uni_z = kwargs.get("uni_z", None) |
|
208 | 1 | if uni_z and uni_z != self.uni_z: |
|
209 | 1 | try: |
|
210 | 1 | self._use_uni_vlan(uni_z, uni_dif=self.uni_z) |
|
211 | 1 | self.make_uni_vlan_available(self.uni_z, uni_dif=uni_z) |
|
212 | 1 | except KytosTagError as err: |
|
213 | 1 | if uni_a_flag: |
|
214 | 1 | self.make_uni_vlan_available(uni_a, uni_dif=self.uni_a) |
|
215 | 1 | raise err |
|
216 | else: |
||
217 | 1 | uni_z = self.uni_z |
|
218 | |||
219 | 1 | if uni_a_flag: |
|
220 | 1 | self.make_uni_vlan_available(self.uni_a, uni_dif=uni_a) |
|
221 | else: |
||
222 | 1 | uni_a = self.uni_a |
|
223 | 1 | return uni_a, uni_z |
|
224 | |||
225 | 1 | def update(self, **kwargs): |
|
226 | """Update evc attributes. |
||
227 | |||
228 | This method will raises an error trying to change the following |
||
229 | attributes: [creation_time, active, current_path, failover_path, |
||
230 | _id, archived] |
||
231 | [name, uni_a and uni_z] |
||
232 | |||
233 | Returns: |
||
234 | the values for enable and a redeploy attribute, if exists and None |
||
235 | otherwise |
||
236 | Raises: |
||
237 | ValueError: message with error detail. |
||
238 | |||
239 | """ |
||
240 | 1 | enable, redeploy = (None, None) |
|
241 | 1 | if not self._tag_lists_equal(**kwargs): |
|
242 | 1 | raise ValueError( |
|
243 | "UNI_A and UNI_Z tag lists should be the same." |
||
244 | ) |
||
245 | 1 | uni_a, uni_z = self._get_unis_use_tags(**kwargs) |
|
246 | 1 | check_disabled_component(uni_a, uni_z) |
|
247 | 1 | self._validate_has_primary_or_dynamic( |
|
248 | primary_path=kwargs.get("primary_path"), |
||
249 | dynamic_backup_path=kwargs.get("dynamic_backup_path"), |
||
250 | uni_a=uni_a, |
||
251 | uni_z=uni_z, |
||
252 | ) |
||
253 | 1 | for attribute, value in kwargs.items(): |
|
254 | 1 | if attribute not in self.updatable_attributes: |
|
255 | 1 | raise ValueError(f"{attribute} can't be updated.") |
|
256 | 1 | if attribute in ("primary_path", "backup_path"): |
|
257 | 1 | try: |
|
258 | 1 | value.is_valid( |
|
259 | uni_a.interface.switch, uni_z.interface.switch |
||
260 | ) |
||
261 | 1 | except InvalidPath as exception: |
|
262 | 1 | raise ValueError( # pylint: disable=raise-missing-from |
|
263 | f"{attribute} is not a " f"valid path: {exception}" |
||
264 | ) |
||
265 | 1 | for attribute, value in kwargs.items(): |
|
266 | 1 | if attribute == "enabled": |
|
267 | 1 | if value: |
|
268 | 1 | self.enable() |
|
269 | else: |
||
270 | 1 | self.disable() |
|
271 | 1 | enable = value |
|
272 | else: |
||
273 | 1 | setattr(self, attribute, value) |
|
274 | 1 | if attribute in self.attributes_requiring_redeploy: |
|
275 | 1 | redeploy = True |
|
276 | 1 | self.sync(set(kwargs.keys())) |
|
277 | 1 | return enable, redeploy |
|
278 | |||
279 | 1 | def set_flow_removed_at(self): |
|
280 | """Update flow_removed_at attribute.""" |
||
281 | self.flow_removed_at = now() |
||
282 | |||
283 | 1 | def has_recent_removed_flow(self, setting=settings): |
|
284 | """Check if any flow has been removed from the evc""" |
||
285 | if self.flow_removed_at is None: |
||
286 | return False |
||
287 | res_seconds = (now() - self.flow_removed_at).seconds |
||
288 | return res_seconds < setting.TIME_RECENT_DELETED_FLOWS |
||
289 | |||
290 | 1 | def is_recent_updated(self, setting=settings): |
|
291 | """Check if the evc has been updated recently""" |
||
292 | res_seconds = (now() - self.updated_at).seconds |
||
293 | return res_seconds < setting.TIME_RECENT_UPDATED |
||
294 | |||
295 | 1 | def __repr__(self): |
|
296 | """Repr method.""" |
||
297 | 1 | return f"EVC({self._id}, {self.name})" |
|
298 | |||
299 | 1 | def _validate(self, **kwargs): |
|
300 | """Do Basic validations. |
||
301 | |||
302 | Verify required attributes: name, uni_a, uni_z |
||
303 | |||
304 | Raises: |
||
305 | ValueError: message with error detail. |
||
306 | |||
307 | """ |
||
308 | 1 | for attribute in self.required_attributes: |
|
309 | |||
310 | 1 | if attribute not in kwargs: |
|
311 | 1 | raise ValueError(f"{attribute} is required.") |
|
312 | |||
313 | 1 | if "uni" in attribute: |
|
314 | 1 | uni = kwargs.get(attribute) |
|
315 | 1 | if not isinstance(uni, UNI): |
|
316 | raise ValueError(f"{attribute} is an invalid UNI.") |
||
317 | |||
318 | 1 | def _tag_lists_equal(self, **kwargs): |
|
319 | """Verify that tag lists are the same.""" |
||
320 | 1 | uni_a = kwargs.get("uni_a") or self.uni_a |
|
321 | 1 | uni_z = kwargs.get("uni_z") or self.uni_z |
|
322 | 1 | uni_a_list = uni_z_list = False |
|
323 | 1 | if (uni_a.user_tag and isinstance(uni_a.user_tag, TAGRange)): |
|
324 | 1 | uni_a_list = True |
|
325 | 1 | if (uni_z.user_tag and isinstance(uni_z.user_tag, TAGRange)): |
|
326 | 1 | uni_z_list = True |
|
327 | 1 | if uni_a_list and uni_z_list: |
|
328 | 1 | return uni_a.user_tag.value == uni_z.user_tag.value |
|
329 | 1 | return uni_a_list == uni_z_list |
|
330 | |||
331 | 1 | def _validate_has_primary_or_dynamic( |
|
332 | self, |
||
333 | primary_path=None, |
||
334 | dynamic_backup_path=None, |
||
335 | uni_a=None, |
||
336 | uni_z=None, |
||
337 | ) -> None: |
||
338 | """Validate that it must have a primary path or allow dynamic paths.""" |
||
339 | 1 | primary_path = ( |
|
340 | primary_path |
||
341 | if primary_path is not None |
||
342 | else self.primary_path |
||
343 | ) |
||
344 | 1 | dynamic_backup_path = ( |
|
345 | dynamic_backup_path |
||
346 | if dynamic_backup_path is not None |
||
347 | else self.dynamic_backup_path |
||
348 | ) |
||
349 | 1 | uni_a = uni_a if uni_a is not None else self.uni_a |
|
350 | 1 | uni_z = uni_z if uni_z is not None else self.uni_z |
|
351 | 1 | if ( |
|
352 | not primary_path |
||
353 | and not dynamic_backup_path |
||
354 | and uni_a and uni_z |
||
355 | and uni_a.interface.switch != uni_z.interface.switch |
||
356 | ): |
||
357 | 1 | msg = "The EVC must have a primary path or allow dynamic paths." |
|
358 | 1 | raise ValueError(msg) |
|
359 | |||
360 | 1 | def __eq__(self, other): |
|
361 | """Override the default implementation.""" |
||
362 | 1 | if not isinstance(other, EVC): |
|
363 | return False |
||
364 | |||
365 | 1 | attrs_to_compare = ["name", "uni_a", "uni_z", "owner", "bandwidth"] |
|
366 | 1 | for attribute in attrs_to_compare: |
|
367 | 1 | if getattr(other, attribute) != getattr(self, attribute): |
|
368 | 1 | return False |
|
369 | 1 | return True |
|
370 | |||
371 | 1 | def is_intra_switch(self): |
|
372 | """Check if the UNIs are in the same switch.""" |
||
373 | 1 | return self.uni_a.interface.switch == self.uni_z.interface.switch |
|
374 | |||
375 | 1 | def check_no_tag_duplicate(self, other_uni: UNI): |
|
376 | """Check if a no tag UNI is duplicated.""" |
||
377 | 1 | if other_uni in (self.uni_a, self.uni_z): |
|
378 | 1 | msg = f"UNI with interface {other_uni.interface.id} is"\ |
|
379 | f" duplicated with {self}." |
||
380 | 1 | raise DuplicatedNoTagUNI(msg) |
|
381 | |||
382 | 1 | def as_dict(self, keys: set = None): |
|
383 | """Return a dictionary representing an EVC object. |
||
384 | keys: Only fields on this variable will be |
||
385 | returned in the dictionary""" |
||
386 | 1 | evc_dict = { |
|
387 | "id": self.id, |
||
388 | "name": self.name, |
||
389 | "uni_a": self.uni_a.as_dict(), |
||
390 | "uni_z": self.uni_z.as_dict(), |
||
391 | } |
||
392 | |||
393 | 1 | time_fmt = "%Y-%m-%dT%H:%M:%S" |
|
394 | |||
395 | 1 | evc_dict["start_date"] = self.start_date |
|
396 | 1 | if isinstance(self.start_date, datetime): |
|
397 | 1 | evc_dict["start_date"] = self.start_date.strftime(time_fmt) |
|
398 | |||
399 | 1 | evc_dict["end_date"] = self.end_date |
|
400 | 1 | if isinstance(self.end_date, datetime): |
|
401 | 1 | evc_dict["end_date"] = self.end_date.strftime(time_fmt) |
|
402 | |||
403 | 1 | evc_dict["queue_id"] = self.queue_id |
|
404 | 1 | evc_dict["bandwidth"] = self.bandwidth |
|
405 | 1 | evc_dict["primary_links"] = self.primary_links.as_dict() |
|
406 | 1 | evc_dict["backup_links"] = self.backup_links.as_dict() |
|
407 | 1 | evc_dict["current_path"] = self.current_path.as_dict() |
|
408 | 1 | evc_dict["failover_path"] = self.failover_path.as_dict() |
|
409 | 1 | evc_dict["primary_path"] = self.primary_path.as_dict() |
|
410 | 1 | evc_dict["backup_path"] = self.backup_path.as_dict() |
|
411 | 1 | evc_dict["dynamic_backup_path"] = self.dynamic_backup_path |
|
412 | 1 | evc_dict["metadata"] = self.metadata |
|
413 | |||
414 | 1 | evc_dict["request_time"] = self.request_time |
|
415 | 1 | if isinstance(self.request_time, datetime): |
|
416 | 1 | evc_dict["request_time"] = self.request_time.strftime(time_fmt) |
|
417 | |||
418 | 1 | time = self.creation_time.strftime(time_fmt) |
|
419 | 1 | evc_dict["creation_time"] = time |
|
420 | |||
421 | 1 | evc_dict["owner"] = self.owner |
|
422 | 1 | evc_dict["circuit_scheduler"] = [ |
|
423 | sc.as_dict() for sc in self.circuit_scheduler |
||
424 | ] |
||
425 | |||
426 | 1 | evc_dict["active"] = self.is_active() |
|
427 | 1 | evc_dict["enabled"] = self.is_enabled() |
|
428 | 1 | evc_dict["archived"] = self.archived |
|
429 | 1 | evc_dict["sb_priority"] = self.sb_priority |
|
430 | 1 | evc_dict["service_level"] = self.service_level |
|
431 | 1 | evc_dict["primary_constraints"] = self.primary_constraints |
|
432 | 1 | evc_dict["secondary_constraints"] = self.secondary_constraints |
|
433 | 1 | evc_dict["flow_removed_at"] = self.flow_removed_at |
|
434 | 1 | evc_dict["updated_at"] = self.updated_at |
|
435 | |||
436 | 1 | if keys: |
|
437 | 1 | selected = {} |
|
438 | 1 | for key in keys: |
|
439 | 1 | selected[key] = evc_dict[key] |
|
440 | 1 | selected["id"] = evc_dict["id"] |
|
441 | 1 | return selected |
|
442 | 1 | return evc_dict |
|
443 | |||
444 | 1 | @property |
|
445 | 1 | def id(self): # pylint: disable=invalid-name |
|
446 | """Return this EVC's ID.""" |
||
447 | 1 | return self._id |
|
448 | |||
449 | 1 | def archive(self): |
|
450 | """Archive this EVC on deletion.""" |
||
451 | 1 | self.archived = True |
|
452 | |||
453 | 1 | def _use_uni_vlan( |
|
454 | self, |
||
455 | uni: UNI, |
||
456 | uni_dif: Union[None, UNI] = None |
||
457 | ): |
||
458 | """Use tags from UNI""" |
||
459 | 1 | if uni.user_tag is None: |
|
460 | 1 | return |
|
461 | 1 | tag = uni.user_tag.value |
|
462 | 1 | tag_type = uni.user_tag.tag_type |
|
463 | 1 | if (uni_dif and isinstance(tag, list) and |
|
464 | isinstance(uni_dif.user_tag.value, list)): |
||
465 | 1 | tag = range_difference(tag, uni_dif.user_tag.value) |
|
466 | 1 | if not tag: |
|
467 | 1 | return |
|
468 | 1 | uni.interface.use_tags( |
|
469 | self._controller, tag, tag_type, use_lock=True, check_order=False |
||
470 | ) |
||
471 | |||
472 | 1 | def make_uni_vlan_available( |
|
473 | self, |
||
474 | uni: UNI, |
||
475 | uni_dif: Union[None, UNI] = None, |
||
476 | ): |
||
477 | """Make available tag from UNI""" |
||
478 | 1 | if uni.user_tag is None: |
|
479 | 1 | return |
|
480 | 1 | tag = uni.user_tag.value |
|
481 | 1 | tag_type = uni.user_tag.tag_type |
|
482 | 1 | if (uni_dif and isinstance(tag, list) and |
|
483 | isinstance(uni_dif.user_tag.value, list)): |
||
484 | 1 | tag = range_difference(tag, uni_dif.user_tag.value) |
|
485 | 1 | if not tag: |
|
486 | return |
||
487 | 1 | try: |
|
488 | 1 | conflict = uni.interface.make_tags_available( |
|
489 | self._controller, tag, tag_type, use_lock=True, |
||
490 | check_order=False |
||
491 | ) |
||
492 | 1 | except KytosTagError as err: |
|
493 | 1 | log.error(f"Error in {self}: {err}") |
|
494 | 1 | return |
|
495 | 1 | if conflict: |
|
496 | 1 | intf = uni.interface.id |
|
497 | 1 | log.warning(f"Tags {conflict} was already available in {intf}") |
|
498 | |||
499 | 1 | def remove_uni_tags(self): |
|
500 | """Remove both UNI usage of a tag""" |
||
501 | 1 | self.make_uni_vlan_available(self.uni_a) |
|
502 | 1 | self.make_uni_vlan_available(self.uni_z) |
|
503 | |||
504 | |||
505 | # pylint: disable=fixme, too-many-public-methods |
||
506 | 1 | class EVCDeploy(EVCBase): |
|
507 | """Class to handle the deploy procedures.""" |
||
508 | |||
509 | 1 | def create(self): |
|
510 | """Create a EVC.""" |
||
511 | |||
512 | 1 | def discover_new_paths(self): |
|
513 | """Discover new paths to satisfy this circuit and deploy it.""" |
||
514 | return DynamicPathManager.get_best_paths(self, |
||
515 | **self.primary_constraints) |
||
516 | |||
517 | 1 | def get_failover_path_candidates(self): |
|
518 | """Get failover paths to satisfy this EVC.""" |
||
519 | # in the future we can return primary/backup paths as well |
||
520 | # we just have to properly handle link_up and failover paths |
||
521 | # if ( |
||
522 | # self.is_using_primary_path() and |
||
523 | # self.backup_path.status is EntityStatus.UP |
||
524 | # ): |
||
525 | # yield self.backup_path |
||
526 | 1 | return DynamicPathManager.get_disjoint_paths(self, self.current_path) |
|
527 | |||
528 | 1 | def change_path(self): |
|
529 | """Change EVC path.""" |
||
530 | |||
531 | 1 | def reprovision(self): |
|
532 | """Force the EVC (re-)provisioning.""" |
||
533 | |||
534 | 1 | def is_affected_by_link(self, link): |
|
535 | """Return True if this EVC has the given link on its current path.""" |
||
536 | 1 | return link in self.current_path |
|
537 | |||
538 | 1 | def link_affected_by_interface(self, interface): |
|
539 | """Return True if this EVC has the given link on its current path.""" |
||
540 | return self.current_path.link_affected_by_interface(interface) |
||
541 | |||
542 | 1 | def is_backup_path_affected_by_link(self, link): |
|
543 | """Return True if the backup path of this EVC uses the given link.""" |
||
544 | 1 | return link in self.backup_path |
|
545 | |||
546 | # pylint: disable=invalid-name |
||
547 | 1 | def is_primary_path_affected_by_link(self, link): |
|
548 | """Return True if the primary path of this EVC uses the given link.""" |
||
549 | 1 | return link in self.primary_path |
|
550 | |||
551 | 1 | def is_failover_path_affected_by_link(self, link): |
|
552 | """Return True if this EVC has the given link on its failover path.""" |
||
553 | 1 | return link in self.failover_path |
|
554 | |||
555 | 1 | def is_eligible_for_failover_path(self): |
|
556 | """Verify if this EVC is eligible for failover path (EP029)""" |
||
557 | # In the future this function can be augmented to consider |
||
558 | # primary/backup, primary/dynamic, and other path combinations |
||
559 | 1 | return ( |
|
560 | self.dynamic_backup_path and |
||
561 | not self.primary_path and not self.backup_path |
||
562 | ) |
||
563 | |||
564 | 1 | def is_using_primary_path(self): |
|
565 | """Verify if the current deployed path is self.primary_path.""" |
||
566 | 1 | return self.primary_path and (self.current_path == self.primary_path) |
|
567 | |||
568 | 1 | def is_using_backup_path(self): |
|
569 | """Verify if the current deployed path is self.backup_path.""" |
||
570 | 1 | return self.backup_path and (self.current_path == self.backup_path) |
|
571 | |||
572 | 1 | def is_using_dynamic_path(self): |
|
573 | """Verify if the current deployed path is a dynamic path.""" |
||
574 | 1 | if ( |
|
575 | self.current_path |
||
576 | and not self.is_using_primary_path() |
||
577 | and not self.is_using_backup_path() |
||
578 | and self.current_path.status == EntityStatus.UP |
||
579 | ): |
||
580 | return True |
||
581 | 1 | return False |
|
582 | |||
583 | 1 | def deploy_to_backup_path(self): |
|
584 | """Deploy the backup path into the datapaths of this circuit. |
||
585 | |||
586 | If the backup_path attribute is valid and up, this method will try to |
||
587 | deploy this backup_path. |
||
588 | |||
589 | If everything fails and dynamic_backup_path is True, then tries to |
||
590 | deploy a dynamic path. |
||
591 | """ |
||
592 | # TODO: Remove flows from current (cookies) |
||
593 | 1 | if self.is_using_backup_path(): |
|
594 | # TODO: Log to say that cannot move backup to backup |
||
595 | return True |
||
596 | |||
597 | 1 | success = False |
|
598 | 1 | if self.backup_path.status is EntityStatus.UP: |
|
599 | 1 | success = self.deploy_to_path(self.backup_path) |
|
600 | |||
601 | 1 | if success: |
|
602 | 1 | return True |
|
603 | |||
604 | 1 | if self.dynamic_backup_path or self.is_intra_switch(): |
|
605 | 1 | return self.deploy_to_path() |
|
606 | |||
607 | return False |
||
608 | |||
609 | 1 | def deploy_to_primary_path(self): |
|
610 | """Deploy the primary path into the datapaths of this circuit. |
||
611 | |||
612 | If the primary_path attribute is valid and up, this method will try to |
||
613 | deploy this primary_path. |
||
614 | """ |
||
615 | # TODO: Remove flows from current (cookies) |
||
616 | 1 | if self.is_using_primary_path(): |
|
617 | # TODO: Log to say that cannot move primary to primary |
||
618 | return True |
||
619 | |||
620 | 1 | if self.primary_path.status is EntityStatus.UP: |
|
621 | 1 | return self.deploy_to_path(self.primary_path) |
|
622 | return False |
||
623 | |||
624 | 1 | def deploy(self): |
|
625 | """Deploy EVC to best path. |
||
626 | |||
627 | Best path can be the primary path, if available. If not, the backup |
||
628 | path, and, if it is also not available, a dynamic path. |
||
629 | """ |
||
630 | 1 | if self.archived: |
|
631 | 1 | return False |
|
632 | 1 | self.enable() |
|
633 | 1 | success = self.deploy_to_primary_path() |
|
634 | 1 | if not success: |
|
635 | 1 | success = self.deploy_to_backup_path() |
|
636 | |||
637 | 1 | if success: |
|
638 | 1 | emit_event(self._controller, "deployed", |
|
639 | content=map_evc_event_content(self)) |
||
640 | 1 | return success |
|
641 | |||
642 | 1 | @staticmethod |
|
643 | 1 | def get_path_status(path): |
|
644 | """Check for the current status of a path. |
||
645 | |||
646 | If any link in this path is down, the path is considered down. |
||
647 | """ |
||
648 | 1 | if not path: |
|
649 | 1 | return EntityStatus.DISABLED |
|
650 | |||
651 | 1 | for link in path: |
|
652 | 1 | if link.status is not EntityStatus.UP: |
|
653 | 1 | return link.status |
|
654 | 1 | return EntityStatus.UP |
|
655 | |||
656 | # def discover_new_path(self): |
||
657 | # # TODO: discover a new path to satisfy this circuit and deploy |
||
658 | |||
659 | 1 | def remove(self): |
|
660 | """Remove EVC path and disable it.""" |
||
661 | 1 | self.remove_current_flows(sync=False) |
|
662 | 1 | self.remove_failover_flows(sync=False) |
|
663 | 1 | self.disable() |
|
664 | 1 | self.sync() |
|
665 | 1 | emit_event(self._controller, "undeployed", |
|
666 | content=map_evc_event_content(self)) |
||
667 | |||
668 | 1 | def remove_failover_flows(self, exclude_uni_switches=True, |
|
669 | force=True, sync=True) -> None: |
||
670 | """Remove failover_flows. |
||
671 | |||
672 | By default, it'll exclude UNI switches, if mef_eline has already |
||
673 | called remove_current_flows before then this minimizes the number |
||
674 | of FlowMods and IO. |
||
675 | """ |
||
676 | 1 | if not self.failover_path: |
|
677 | 1 | return |
|
678 | 1 | switches, cookie, excluded = set(), self.get_cookie(), set() |
|
679 | 1 | if exclude_uni_switches: |
|
680 | 1 | excluded.add(self.uni_a.interface.switch.id) |
|
681 | 1 | excluded.add(self.uni_z.interface.switch.id) |
|
682 | 1 | for link in self.failover_path: |
|
683 | 1 | if link.endpoint_a.switch.id not in excluded: |
|
684 | 1 | switches.add(link.endpoint_a.switch.id) |
|
685 | 1 | if link.endpoint_b.switch.id not in excluded: |
|
686 | 1 | switches.add(link.endpoint_b.switch.id) |
|
687 | 1 | flow_mods = { |
|
688 | "switches": list(switches), |
||
689 | "flows": [{ |
||
690 | "cookie": cookie, |
||
691 | "cookie_mask": int(0xffffffffffffffff), |
||
692 | "owner": "mef_eline", |
||
693 | }] |
||
694 | } |
||
695 | 1 | try: |
|
696 | 1 | self._send_flow_mods( |
|
697 | flow_mods, |
||
698 | "delete", |
||
699 | force=force, |
||
700 | ) |
||
701 | except FlowModException as err: |
||
702 | log.error(f"Error deleting {self} failover_path flows, {err}") |
||
703 | 1 | try: |
|
704 | 1 | self.failover_path.make_vlans_available(self._controller) |
|
705 | except KytosTagError as err: |
||
706 | log.error(f"Error removing {self} failover_path: {err}") |
||
707 | 1 | self.failover_path = Path([]) |
|
708 | 1 | if sync: |
|
709 | 1 | self.sync() |
|
710 | |||
711 | 1 | def remove_current_flows(self, force=True, sync=True): |
|
712 | """Remove all flows from current path or path intended for |
||
713 | current path if exists.""" |
||
714 | 1 | switches = set() |
|
715 | |||
716 | 1 | if not self.current_path and not self.is_intra_switch(): |
|
717 | 1 | return |
|
718 | 1 | current_path = self.current_path |
|
719 | 1 | for link in current_path: |
|
720 | 1 | switches.add(link.endpoint_a.switch.id) |
|
721 | 1 | switches.add(link.endpoint_b.switch.id) |
|
722 | 1 | switches.add(self.uni_a.interface.switch.id) |
|
723 | 1 | switches.add(self.uni_z.interface.switch.id) |
|
724 | 1 | flow_mods = { |
|
725 | "switches": list(switches), |
||
726 | "flows": [{ |
||
727 | "cookie": self.get_cookie(), |
||
728 | "cookie_mask": int(0xffffffffffffffff), |
||
729 | "owner": "mef_eline", |
||
730 | }] |
||
731 | } |
||
732 | |||
733 | 1 | try: |
|
734 | 1 | self._send_flow_mods(flow_mods, "delete", force=force) |
|
735 | 1 | except FlowModException as err: |
|
736 | 1 | log.error(f"Error deleting {self} current_path flows, {err}") |
|
737 | |||
738 | 1 | try: |
|
739 | 1 | current_path.make_vlans_available(self._controller) |
|
740 | except KytosTagError as err: |
||
741 | log.error(f"Error removing {self} current_path: {err}") |
||
742 | 1 | self.current_path = Path([]) |
|
743 | 1 | self.deactivate() |
|
744 | 1 | if sync: |
|
745 | 1 | self.sync() |
|
746 | |||
747 | 1 | def remove_path_flows( |
|
748 | self, path=None, force=True |
||
749 | ) -> dict[str, list[dict]]: |
||
750 | """Remove all flows from path, and return the removed flows.""" |
||
751 | 1 | dpid_flows_match: dict[str, dict] = defaultdict(lambda: {"flows": []}) |
|
752 | 1 | out_flows: dict[str, list[dict]] = defaultdict(list) |
|
753 | |||
754 | 1 | if not path: |
|
755 | 1 | return dpid_flows_match |
|
756 | |||
757 | 1 | try: |
|
758 | 1 | nni_flows = self._prepare_nni_flows(path) |
|
759 | # pylint: disable=broad-except |
||
760 | except Exception: |
||
761 | err = traceback.format_exc().replace("\n", ", ") |
||
762 | log.error(f"Fail to remove NNI failover flows for {self}: {err}") |
||
763 | nni_flows = {} |
||
764 | |||
765 | 1 | for dpid, flows in nni_flows.items(): |
|
766 | 1 | for flow in flows: |
|
767 | 1 | flow_mod = { |
|
768 | "cookie": flow["cookie"], |
||
769 | "match": flow["match"], |
||
770 | "owner": "mef_eline", |
||
771 | "cookie_mask": int(0xffffffffffffffff) |
||
772 | } |
||
773 | 1 | dpid_flows_match[dpid]["flows"].append(flow_mod) |
|
774 | 1 | out_flows[dpid].append(flow_mod) |
|
775 | |||
776 | 1 | try: |
|
777 | 1 | uni_flows = self._prepare_uni_flows(path, skip_in=True) |
|
778 | # pylint: disable=broad-except |
||
779 | except Exception: |
||
780 | err = traceback.format_exc().replace("\n", ", ") |
||
781 | log.error(f"Fail to remove UNI failover flows for {self}: {err}") |
||
782 | uni_flows = {} |
||
783 | |||
784 | 1 | for dpid, flows in uni_flows.items(): |
|
785 | 1 | for flow in flows: |
|
786 | 1 | flow_mod = { |
|
787 | "cookie": flow["cookie"], |
||
788 | "match": flow["match"], |
||
789 | "owner": "mef_eline", |
||
790 | "cookie_mask": int(0xffffffffffffffff) |
||
791 | } |
||
792 | 1 | dpid_flows_match[dpid]["flows"].append(flow_mod) |
|
793 | 1 | out_flows[dpid].append(flow_mod) |
|
794 | |||
795 | 1 | try: |
|
796 | 1 | self._send_flow_mods( |
|
797 | dpid_flows_match, 'delete', force=force, by_switch=True |
||
798 | ) |
||
799 | 1 | except FlowModException as err: |
|
800 | 1 | log.error( |
|
801 | f"Error deleting {self} path flows, path:{path}, error={err}" |
||
802 | ) |
||
803 | |||
804 | 1 | try: |
|
805 | 1 | path.make_vlans_available(self._controller) |
|
806 | except KytosTagError as err: |
||
807 | log.error(f"Error removing {self} path: {err}") |
||
808 | |||
809 | 1 | return out_flows |
|
810 | |||
811 | 1 | @staticmethod |
|
812 | 1 | def links_zipped(path=None): |
|
813 | """Return an iterator which yields pairs of links in order.""" |
||
814 | 1 | if not path: |
|
815 | 1 | return [] |
|
816 | 1 | return zip(path[:-1], path[1:]) |
|
817 | |||
818 | 1 | def should_deploy(self, path=None): |
|
819 | """Verify if the circuit should be deployed.""" |
||
820 | 1 | if not path: |
|
821 | 1 | log.debug("Path is empty.") |
|
822 | 1 | return False |
|
823 | |||
824 | 1 | if not self.is_enabled(): |
|
825 | 1 | log.debug(f"{self} is disabled.") |
|
826 | 1 | return False |
|
827 | |||
828 | 1 | if not self.is_active(): |
|
829 | 1 | log.debug(f"{self} will be deployed.") |
|
830 | 1 | return True |
|
831 | |||
832 | 1 | return False |
|
833 | |||
834 | 1 | @staticmethod |
|
835 | 1 | def is_uni_interface_active( |
|
836 | *interfaces: Interface |
||
837 | ) -> tuple[bool, dict]: |
||
838 | """Whether UNIs are active and their status & status_reason.""" |
||
839 | 1 | active = True |
|
840 | 1 | bad_interfaces = [ |
|
841 | interface |
||
842 | for interface in interfaces |
||
843 | if interface.status != EntityStatus.UP |
||
844 | ] |
||
845 | 1 | if bad_interfaces: |
|
846 | 1 | active = False |
|
847 | 1 | interfaces = bad_interfaces |
|
848 | 1 | return active, { |
|
849 | interface.id: { |
||
850 | 'status': interface.status.value, |
||
851 | 'status_reason': interface.status_reason, |
||
852 | } |
||
853 | for interface in interfaces |
||
854 | } |
||
855 | |||
856 | 1 | def try_to_activate(self) -> bool: |
|
857 | """Try to activate the EVC.""" |
||
858 | 1 | if self.is_intra_switch(): |
|
859 | 1 | return self._try_to_activate_intra_evc() |
|
860 | 1 | return self._try_to_activate_inter_evc() |
|
861 | |||
862 | 1 | def _try_to_activate_intra_evc(self) -> bool: |
|
863 | """Try to activate intra EVC.""" |
||
864 | 1 | intf_a, intf_z = self.uni_a.interface, self.uni_z.interface |
|
865 | 1 | is_active, reason = self.is_uni_interface_active(intf_a, intf_z) |
|
866 | 1 | if not is_active: |
|
867 | 1 | raise ActivationError( |
|
868 | f"Won't be able to activate {self} due to UNIs: {reason}" |
||
869 | ) |
||
870 | 1 | self.activate() |
|
871 | 1 | return True |
|
872 | |||
873 | 1 | def _try_to_activate_inter_evc(self) -> bool: |
|
874 | """Try to activate inter EVC.""" |
||
875 | 1 | intf_a, intf_z = self.uni_a.interface, self.uni_z.interface |
|
876 | 1 | is_active, reason = self.is_uni_interface_active(intf_a, intf_z) |
|
877 | 1 | if not is_active: |
|
878 | 1 | raise ActivationError( |
|
879 | f"Won't be able to activate {self} due to UNIs: {reason}" |
||
880 | ) |
||
881 | 1 | if self.current_path.status != EntityStatus.UP: |
|
882 | 1 | raise ActivationError( |
|
883 | f"Won't be able to activate {self} due to current_path " |
||
884 | f"status {self.current_path.status}" |
||
885 | ) |
||
886 | 1 | self.activate() |
|
887 | 1 | return True |
|
888 | |||
889 | # pylint: disable=too-many-branches, too-many-statements |
||
890 | 1 | def deploy_to_path(self, path=None): |
|
891 | """Install the flows for this circuit. |
||
892 | |||
893 | Procedures to deploy: |
||
894 | |||
895 | 0. Remove current flows installed |
||
896 | 1. Decide if will deploy "path" or discover a new path |
||
897 | 2. Choose vlan |
||
898 | 3. Install NNI flows |
||
899 | 4. Install UNI flows |
||
900 | 5. Activate |
||
901 | 6. Update current_path |
||
902 | 7. Update links caches(primary, current, backup) |
||
903 | |||
904 | """ |
||
905 | 1 | self.remove_current_flows(sync=False) |
|
906 | 1 | use_path = path or Path([]) |
|
907 | 1 | tag_errors = [] |
|
908 | 1 | if self.should_deploy(use_path): |
|
909 | 1 | try: |
|
910 | 1 | use_path.choose_vlans(self._controller) |
|
911 | 1 | except KytosNoTagAvailableError as e: |
|
912 | 1 | tag_errors.append(str(e)) |
|
913 | 1 | use_path = None |
|
914 | else: |
||
915 | 1 | for use_path in self.discover_new_paths(): |
|
916 | 1 | if use_path is None: |
|
917 | continue |
||
918 | 1 | try: |
|
919 | 1 | use_path.choose_vlans(self._controller) |
|
920 | 1 | break |
|
921 | 1 | except KytosNoTagAvailableError as e: |
|
922 | 1 | tag_errors.append(str(e)) |
|
923 | else: |
||
924 | 1 | use_path = None |
|
925 | |||
926 | 1 | try: |
|
927 | 1 | if use_path: |
|
928 | 1 | self._install_flows(use_path) |
|
929 | 1 | elif self.is_intra_switch(): |
|
930 | 1 | use_path = Path() |
|
931 | 1 | self._install_direct_uni_flows() |
|
932 | else: |
||
933 | 1 | msg = f"{self} was not deployed. No available path was found." |
|
934 | 1 | if tag_errors: |
|
935 | 1 | msg = self.add_tag_errors(msg, tag_errors) |
|
936 | 1 | log.error(msg) |
|
937 | else: |
||
938 | 1 | log.warning(msg) |
|
939 | 1 | return False |
|
940 | 1 | except EVCPathNotInstalled as err: |
|
941 | 1 | log.error( |
|
942 | f"Error deploying EVC {self} when calling flow_manager: {err}" |
||
943 | ) |
||
944 | 1 | self.remove_current_flows(use_path, sync=True) |
|
945 | 1 | return False |
|
946 | |||
947 | 1 | self.current_path = use_path |
|
948 | 1 | msg = f"{self} was deployed." |
|
949 | 1 | try: |
|
950 | 1 | self.try_to_activate() |
|
951 | except ActivationError as exc: |
||
952 | msg = f"{msg} {str(exc)}" |
||
953 | 1 | self.sync() |
|
954 | 1 | log.info(msg) |
|
955 | 1 | return True |
|
956 | |||
957 | 1 | def try_setup_failover_path(self, wait=settings.DEPLOY_EVCS_INTERVAL): |
|
958 | """Try setup failover_path whenever possible.""" |
||
959 | 1 | if ( |
|
960 | self.failover_path or not self.current_path |
||
961 | or not self.is_active() |
||
962 | ): |
||
963 | 1 | return |
|
964 | 1 | if (now() - self.affected_by_link_at).seconds >= wait: |
|
965 | 1 | with self.lock: |
|
966 | 1 | self.setup_failover_path() |
|
967 | |||
968 | # pylint: disable=too-many-statements |
||
969 | 1 | def setup_failover_path(self): |
|
970 | """Install flows for the failover path of this EVC. |
||
971 | |||
972 | Procedures to deploy: |
||
973 | |||
974 | 0. Remove flows currently installed for failover_path (if any) |
||
975 | 1. Discover a disjoint path from current_path |
||
976 | 2. Choose vlans |
||
977 | 3. Install NNI flows |
||
978 | 4. Install UNI egress flows |
||
979 | 5. Update failover_path |
||
980 | """ |
||
981 | # Intra-switch EVCs have no failover_path |
||
982 | 1 | if self.is_intra_switch(): |
|
983 | 1 | return False |
|
984 | |||
985 | # For not only setup failover path for totally dynamic EVCs |
||
986 | 1 | if not self.is_eligible_for_failover_path(): |
|
987 | 1 | return False |
|
988 | |||
989 | 1 | out_new_flows: dict[str, list[dict]] = {} |
|
990 | 1 | reason = "" |
|
991 | 1 | tag_errors = [] |
|
992 | 1 | out_removed_flows = self.remove_path_flows(self.failover_path) |
|
993 | 1 | self.failover_path = Path([]) |
|
994 | |||
995 | 1 | for use_path in self.get_failover_path_candidates(): |
|
996 | 1 | if not use_path: |
|
997 | 1 | continue |
|
998 | 1 | try: |
|
999 | 1 | use_path.choose_vlans(self._controller) |
|
1000 | 1 | break |
|
1001 | 1 | except KytosNoTagAvailableError as e: |
|
1002 | 1 | tag_errors.append(str(e)) |
|
1003 | else: |
||
1004 | 1 | use_path = Path([]) |
|
1005 | 1 | reason = "No available path was found" |
|
1006 | |||
1007 | 1 | try: |
|
1008 | 1 | if use_path: |
|
1009 | 1 | out_new_flows = self._install_flows( |
|
1010 | use_path, skip_in=True |
||
1011 | ) |
||
1012 | 1 | except EVCPathNotInstalled as err: |
|
1013 | 1 | reason = "Error deploying failover path" |
|
1014 | 1 | log.error( |
|
1015 | f"{reason} for {self}. FlowManager error: {err}" |
||
1016 | ) |
||
1017 | 1 | _rmed_flows = self.remove_path_flows(use_path) |
|
1018 | 1 | out_removed_flows = merge_flow_dicts( |
|
1019 | out_removed_flows, _rmed_flows |
||
1020 | ) |
||
1021 | 1 | use_path = Path([]) |
|
1022 | |||
1023 | 1 | self.failover_path = use_path |
|
1024 | 1 | self.sync() |
|
1025 | |||
1026 | 1 | if out_new_flows or out_removed_flows: |
|
1027 | 1 | emit_event(self._controller, "failover_deployed", content={ |
|
1028 | self.id: map_evc_event_content( |
||
1029 | self, |
||
1030 | flows=deepcopy(out_new_flows), |
||
1031 | removed_flows=deepcopy(out_removed_flows), |
||
1032 | error_reason=reason, |
||
1033 | current_path=self.current_path.as_dict(), |
||
1034 | ) |
||
1035 | }) |
||
1036 | |||
1037 | 1 | if not use_path: |
|
1038 | 1 | msg = f"Failover path for {self} was not deployed: {reason}." |
|
1039 | 1 | if tag_errors: |
|
1040 | 1 | msg = self.add_tag_errors(msg, tag_errors) |
|
1041 | 1 | log.error(msg) |
|
1042 | else: |
||
1043 | 1 | log.warning(msg) |
|
1044 | 1 | return False |
|
1045 | 1 | log.info(f"Failover path for {self} was deployed.") |
|
1046 | 1 | return True |
|
1047 | |||
1048 | 1 | @staticmethod |
|
1049 | 1 | def add_tag_errors(msg: str, tag_errors: list): |
|
1050 | """Add to msg the tag errors ecountered when chossing path.""" |
||
1051 | 1 | path = ['path', 'paths'] |
|
1052 | 1 | was = ['was', 'were'] |
|
1053 | 1 | message = ['message', 'messages'] |
|
1054 | |||
1055 | # Choose either singular(0) or plural(1) words |
||
1056 | 1 | n = 1 |
|
1057 | 1 | if len(tag_errors) == 1: |
|
1058 | 1 | n = 0 |
|
1059 | |||
1060 | 1 | msg += f" {len(tag_errors)} {path[n]} {was[n]} rejected" |
|
1061 | 1 | msg += f" with {message[n]}: {tag_errors}" |
|
1062 | 1 | return msg |
|
1063 | |||
1064 | 1 | def get_failover_flows(self): |
|
1065 | """Return the flows needed to make the failover path active, i.e. the |
||
1066 | flows for ingress forwarding. |
||
1067 | |||
1068 | Return: |
||
1069 | dict: A dict of flows indexed by the switch_id will be returned, or |
||
1070 | an empty dict if no failover_path is available. |
||
1071 | """ |
||
1072 | 1 | if not self.failover_path: |
|
1073 | 1 | return {} |
|
1074 | 1 | return self._prepare_uni_flows(self.failover_path, skip_out=True) |
|
1075 | |||
1076 | # pylint: disable=too-many-branches |
||
1077 | 1 | def _prepare_direct_uni_flows(self): |
|
1078 | """Prepare flows connecting two UNIs for intra-switch EVC.""" |
||
1079 | 1 | vlan_a = self._get_value_from_uni_tag(self.uni_a) |
|
1080 | 1 | vlan_z = self._get_value_from_uni_tag(self.uni_z) |
|
1081 | |||
1082 | 1 | flow_mod_az = self._prepare_flow_mod( |
|
1083 | self.uni_a.interface, self.uni_z.interface, |
||
1084 | self.queue_id, vlan_a |
||
1085 | ) |
||
1086 | 1 | flow_mod_za = self._prepare_flow_mod( |
|
1087 | self.uni_z.interface, self.uni_a.interface, |
||
1088 | self.queue_id, vlan_z |
||
1089 | ) |
||
1090 | |||
1091 | 1 | View Code Duplication | if not isinstance(vlan_z, list) and vlan_z not in self.special_cases: |
|
|||
1092 | 1 | flow_mod_az["actions"].insert( |
|
1093 | 0, {"action_type": "set_vlan", "vlan_id": vlan_z} |
||
1094 | ) |
||
1095 | 1 | if not vlan_a: |
|
1096 | 1 | flow_mod_az["actions"].insert( |
|
1097 | 0, {"action_type": "push_vlan", "tag_type": "c"} |
||
1098 | ) |
||
1099 | 1 | if vlan_a == 0: |
|
1100 | 1 | flow_mod_za["actions"].insert(0, {"action_type": "pop_vlan"}) |
|
1101 | 1 | elif vlan_a == 0 and vlan_z == "4096/4096": |
|
1102 | 1 | flow_mod_za["actions"].insert(0, {"action_type": "pop_vlan"}) |
|
1103 | |||
1104 | 1 | View Code Duplication | if not isinstance(vlan_a, list) and vlan_a not in self.special_cases: |
1105 | 1 | flow_mod_za["actions"].insert( |
|
1106 | 0, {"action_type": "set_vlan", "vlan_id": vlan_a} |
||
1107 | ) |
||
1108 | 1 | if not vlan_z: |
|
1109 | 1 | flow_mod_za["actions"].insert( |
|
1110 | 0, {"action_type": "push_vlan", "tag_type": "c"} |
||
1111 | ) |
||
1112 | 1 | if vlan_z == 0: |
|
1113 | 1 | flow_mod_az["actions"].insert(0, {"action_type": "pop_vlan"}) |
|
1114 | 1 | elif vlan_a == "4096/4096" and vlan_z == 0: |
|
1115 | 1 | flow_mod_az["actions"].insert(0, {"action_type": "pop_vlan"}) |
|
1116 | |||
1117 | 1 | flows = [] |
|
1118 | 1 | if isinstance(vlan_a, list): |
|
1119 | 1 | for mask_a in vlan_a: |
|
1120 | 1 | flow_aux = deepcopy(flow_mod_az) |
|
1121 | 1 | flow_aux["match"]["dl_vlan"] = mask_a |
|
1122 | 1 | flows.append(flow_aux) |
|
1123 | else: |
||
1124 | 1 | if vlan_a is not None: |
|
1125 | 1 | flow_mod_az["match"]["dl_vlan"] = vlan_a |
|
1126 | 1 | flows.append(flow_mod_az) |
|
1127 | |||
1128 | 1 | if isinstance(vlan_z, list): |
|
1129 | 1 | for mask_z in vlan_z: |
|
1130 | 1 | flow_aux = deepcopy(flow_mod_za) |
|
1131 | 1 | flow_aux["match"]["dl_vlan"] = mask_z |
|
1132 | 1 | flows.append(flow_aux) |
|
1133 | else: |
||
1134 | 1 | if vlan_z is not None: |
|
1135 | 1 | flow_mod_za["match"]["dl_vlan"] = vlan_z |
|
1136 | 1 | flows.append(flow_mod_za) |
|
1137 | 1 | return ( |
|
1138 | self.uni_a.interface.switch.id, flows |
||
1139 | ) |
||
1140 | |||
1141 | 1 | def _install_direct_uni_flows(self): |
|
1142 | """Install flows connecting two UNIs. |
||
1143 | |||
1144 | This case happens when the circuit is between UNIs in the |
||
1145 | same switch. |
||
1146 | """ |
||
1147 | 1 | (dpid, flows) = self._prepare_direct_uni_flows() |
|
1148 | 1 | flow_mods = {"switches": [dpid], "flows": flows} |
|
1149 | 1 | try: |
|
1150 | 1 | self._send_flow_mods(flow_mods, "install") |
|
1151 | 1 | except FlowModException as err: |
|
1152 | 1 | raise EVCPathNotInstalled(str(err)) from err |
|
1153 | |||
1154 | 1 | def _prepare_nni_flows(self, path=None): |
|
1155 | """Prepare NNI flows.""" |
||
1156 | 1 | nni_flows = OrderedDict() |
|
1157 | 1 | previous = self.uni_a.interface.switch.dpid |
|
1158 | 1 | for incoming, outcoming in self.links_zipped(path): |
|
1159 | 1 | in_vlan = incoming.get_metadata("s_vlan").value |
|
1160 | 1 | out_vlan = outcoming.get_metadata("s_vlan").value |
|
1161 | 1 | in_endpoint = self.get_endpoint_by_id(incoming, previous, ne) |
|
1162 | 1 | out_endpoint = self.get_endpoint_by_id( |
|
1163 | outcoming, in_endpoint.switch.id, eq |
||
1164 | ) |
||
1165 | |||
1166 | 1 | flows = [] |
|
1167 | # Flow for one direction |
||
1168 | 1 | flows.append( |
|
1169 | self._prepare_nni_flow( |
||
1170 | in_endpoint, |
||
1171 | out_endpoint, |
||
1172 | in_vlan, |
||
1173 | out_vlan, |
||
1174 | queue_id=self.queue_id, |
||
1175 | ) |
||
1176 | ) |
||
1177 | |||
1178 | # Flow for the other direction |
||
1179 | 1 | flows.append( |
|
1180 | self._prepare_nni_flow( |
||
1181 | out_endpoint, |
||
1182 | in_endpoint, |
||
1183 | out_vlan, |
||
1184 | in_vlan, |
||
1185 | queue_id=self.queue_id, |
||
1186 | ) |
||
1187 | ) |
||
1188 | 1 | previous = in_endpoint.switch.id |
|
1189 | 1 | nni_flows[in_endpoint.switch.id] = flows |
|
1190 | 1 | return nni_flows |
|
1191 | |||
1192 | 1 | def _install_flows( |
|
1193 | self, path=None, skip_in=False, skip_out=False |
||
1194 | ) -> dict[str, list[dict]]: |
||
1195 | """Install uni and nni flows""" |
||
1196 | 1 | flows_by_switch = defaultdict(lambda: {"flows": []}) |
|
1197 | 1 | new_flows = defaultdict(list) |
|
1198 | 1 | for dpid, flows in self._prepare_nni_flows(path).items(): |
|
1199 | 1 | flows_by_switch[dpid]["flows"].extend(flows) |
|
1200 | 1 | new_flows[dpid].extend(flows) |
|
1201 | 1 | for dpid, flows in self._prepare_uni_flows( |
|
1202 | path, skip_in, skip_out |
||
1203 | ).items(): |
||
1204 | 1 | flows_by_switch[dpid]["flows"].extend(flows) |
|
1205 | 1 | new_flows[dpid].extend(flows) |
|
1206 | |||
1207 | 1 | try: |
|
1208 | 1 | self._send_flow_mods(flows_by_switch, "install", by_switch=True) |
|
1209 | 1 | except FlowModException as err: |
|
1210 | 1 | raise EVCPathNotInstalled(str(err)) from err |
|
1211 | |||
1212 | 1 | return new_flows |
|
1213 | |||
1214 | 1 | @staticmethod |
|
1215 | 1 | def _get_value_from_uni_tag(uni: UNI): |
|
1216 | """Returns the value from tag. In case of any and untagged |
||
1217 | it should return 4096/4096 and 0 respectively""" |
||
1218 | 1 | special = {"any": "4096/4096", "untagged": 0} |
|
1219 | 1 | if uni.user_tag: |
|
1220 | 1 | value = uni.user_tag.value |
|
1221 | 1 | if isinstance(value, list): |
|
1222 | 1 | return uni.user_tag.mask_list |
|
1223 | 1 | return special.get(value, value) |
|
1224 | 1 | return None |
|
1225 | |||
1226 | # pylint: disable=too-many-locals |
||
1227 | 1 | def _prepare_uni_flows(self, path=None, skip_in=False, skip_out=False): |
|
1228 | """Prepare flows to install UNIs.""" |
||
1229 | 1 | uni_flows = {} |
|
1230 | 1 | if not path: |
|
1231 | log.info("install uni flows without path.") |
||
1232 | return uni_flows |
||
1233 | |||
1234 | # Determine VLANs |
||
1235 | 1 | in_vlan_a = self._get_value_from_uni_tag(self.uni_a) |
|
1236 | 1 | out_vlan_a = path[0].get_metadata("s_vlan").value |
|
1237 | |||
1238 | 1 | in_vlan_z = self._get_value_from_uni_tag(self.uni_z) |
|
1239 | 1 | out_vlan_z = path[-1].get_metadata("s_vlan").value |
|
1240 | |||
1241 | # Get endpoints from path |
||
1242 | 1 | endpoint_a = self.get_endpoint_by_id( |
|
1243 | path[0], self.uni_a.interface.switch.id, eq |
||
1244 | ) |
||
1245 | 1 | endpoint_z = self.get_endpoint_by_id( |
|
1246 | path[-1], self.uni_z.interface.switch.id, eq |
||
1247 | ) |
||
1248 | |||
1249 | # Flows for the first UNI |
||
1250 | 1 | flows_a = [] |
|
1251 | |||
1252 | # Flow for one direction, pushing the service tag |
||
1253 | 1 | if not skip_in: |
|
1254 | 1 | if isinstance(in_vlan_a, list): |
|
1255 | 1 | for in_mask_a in in_vlan_a: |
|
1256 | 1 | push_flow = self._prepare_push_flow( |
|
1257 | self.uni_a.interface, |
||
1258 | endpoint_a, |
||
1259 | in_mask_a, |
||
1260 | out_vlan_a, |
||
1261 | in_vlan_z, |
||
1262 | queue_id=self.queue_id, |
||
1263 | ) |
||
1264 | 1 | flows_a.append(push_flow) |
|
1265 | else: |
||
1266 | push_flow = self._prepare_push_flow( |
||
1267 | self.uni_a.interface, |
||
1268 | endpoint_a, |
||
1269 | in_vlan_a, |
||
1270 | out_vlan_a, |
||
1271 | in_vlan_z, |
||
1272 | queue_id=self.queue_id, |
||
1273 | ) |
||
1274 | flows_a.append(push_flow) |
||
1275 | |||
1276 | # Flow for the other direction, popping the service tag |
||
1277 | 1 | if not skip_out: |
|
1278 | 1 | pop_flow = self._prepare_pop_flow( |
|
1279 | endpoint_a, |
||
1280 | self.uni_a.interface, |
||
1281 | out_vlan_a, |
||
1282 | queue_id=self.queue_id, |
||
1283 | ) |
||
1284 | 1 | flows_a.append(pop_flow) |
|
1285 | |||
1286 | 1 | uni_flows[self.uni_a.interface.switch.id] = flows_a |
|
1287 | |||
1288 | # Flows for the second UNI |
||
1289 | 1 | flows_z = [] |
|
1290 | |||
1291 | # Flow for one direction, pushing the service tag |
||
1292 | 1 | if not skip_in: |
|
1293 | 1 | if isinstance(in_vlan_z, list): |
|
1294 | 1 | for in_mask_z in in_vlan_z: |
|
1295 | 1 | push_flow = self._prepare_push_flow( |
|
1296 | self.uni_z.interface, |
||
1297 | endpoint_z, |
||
1298 | in_mask_z, |
||
1299 | out_vlan_z, |
||
1300 | in_vlan_a, |
||
1301 | queue_id=self.queue_id, |
||
1302 | ) |
||
1303 | 1 | flows_z.append(push_flow) |
|
1304 | else: |
||
1305 | push_flow = self._prepare_push_flow( |
||
1306 | self.uni_z.interface, |
||
1307 | endpoint_z, |
||
1308 | in_vlan_z, |
||
1309 | out_vlan_z, |
||
1310 | in_vlan_a, |
||
1311 | queue_id=self.queue_id, |
||
1312 | ) |
||
1313 | flows_z.append(push_flow) |
||
1314 | |||
1315 | # Flow for the other direction, popping the service tag |
||
1316 | 1 | if not skip_out: |
|
1317 | 1 | pop_flow = self._prepare_pop_flow( |
|
1318 | endpoint_z, |
||
1319 | self.uni_z.interface, |
||
1320 | out_vlan_z, |
||
1321 | queue_id=self.queue_id, |
||
1322 | ) |
||
1323 | 1 | flows_z.append(pop_flow) |
|
1324 | |||
1325 | 1 | uni_flows[self.uni_z.interface.switch.id] = flows_z |
|
1326 | |||
1327 | 1 | return uni_flows |
|
1328 | |||
1329 | 1 | @staticmethod |
|
1330 | 1 | @retry( |
|
1331 | stop=stop_after_attempt(3), |
||
1332 | wait=wait_combine(wait_fixed(3), wait_random(min=2, max=7)), |
||
1333 | retry=retry_if_exception_type(FlowModException), |
||
1334 | before_sleep=before_sleep, |
||
1335 | reraise=True, |
||
1336 | ) |
||
1337 | 1 | def _send_flow_mods( |
|
1338 | data_content: dict, |
||
1339 | command="install", |
||
1340 | force=False, |
||
1341 | by_switch=False |
||
1342 | ): |
||
1343 | """Send a flow_mod list to a specific switch. |
||
1344 | |||
1345 | Args: |
||
1346 | dpid(str): The target of flows (i.e. Switch.id). |
||
1347 | flow_mods(dict): Python dictionary with flow_mods. |
||
1348 | command(str): By default is 'flows'. To remove a flow is 'remove'. |
||
1349 | force(bool): True to send via consistency check in case of errors. |
||
1350 | by_switch(bool): True to send to 'flows_by_switch' request instead. |
||
1351 | """ |
||
1352 | 1 | if by_switch: |
|
1353 | 1 | endpoint = f"{settings.MANAGER_URL}/flows_by_switch/?force={force}" |
|
1354 | else: |
||
1355 | 1 | endpoint = f"{settings.MANAGER_URL}/flows" |
|
1356 | 1 | data_content["force"] = force |
|
1357 | 1 | try: |
|
1358 | 1 | if command == "install": |
|
1359 | 1 | res = httpx.post(endpoint, json=data_content, timeout=30) |
|
1360 | 1 | elif command == "delete": |
|
1361 | 1 | res = httpx.request( |
|
1362 | "DELETE", endpoint, json=data_content, timeout=30 |
||
1363 | ) |
||
1364 | 1 | except httpx.RequestError as err: |
|
1365 | 1 | raise FlowModException(str(err)) from err |
|
1366 | 1 | if res.is_server_error or res.status_code >= 400: |
|
1367 | 1 | raise FlowModException(res.text) |
|
1368 | |||
1369 | 1 | def get_cookie(self): |
|
1370 | """Return the cookie integer from evc id.""" |
||
1371 | 1 | return int(self.id, 16) + (settings.COOKIE_PREFIX << 56) |
|
1372 | |||
1373 | 1 | @staticmethod |
|
1374 | 1 | def get_id_from_cookie(cookie): |
|
1375 | """Return the evc id given a cookie value.""" |
||
1376 | 1 | evc_id = cookie - (settings.COOKIE_PREFIX << 56) |
|
1377 | 1 | return f"{evc_id:x}".zfill(14) |
|
1378 | |||
1379 | 1 | def set_flow_table_group_id(self, flow_mod: dict, vlan) -> dict: |
|
1380 | """Set table_group and table_id""" |
||
1381 | 1 | table_group = "epl" if vlan is None else "evpl" |
|
1382 | 1 | flow_mod["table_group"] = table_group |
|
1383 | 1 | flow_mod["table_id"] = self.table_group[table_group] |
|
1384 | 1 | return flow_mod |
|
1385 | |||
1386 | 1 | @staticmethod |
|
1387 | 1 | def get_priority(vlan): |
|
1388 | """Return priority value depending on vlan value""" |
||
1389 | 1 | if isinstance(vlan, list): |
|
1390 | 1 | return settings.EVPL_SB_PRIORITY |
|
1391 | 1 | if vlan not in {None, "4096/4096", 0}: |
|
1392 | 1 | return settings.EVPL_SB_PRIORITY |
|
1393 | 1 | if vlan == 0: |
|
1394 | 1 | return settings.UNTAGGED_SB_PRIORITY |
|
1395 | 1 | if vlan == "4096/4096": |
|
1396 | 1 | return settings.ANY_SB_PRIORITY |
|
1397 | 1 | return settings.EPL_SB_PRIORITY |
|
1398 | |||
1399 | 1 | def _prepare_flow_mod(self, in_interface, out_interface, |
|
1400 | queue_id=None, vlan=True): |
||
1401 | """Prepare a common flow mod.""" |
||
1402 | 1 | default_actions = [ |
|
1403 | {"action_type": "output", "port": out_interface.port_number} |
||
1404 | ] |
||
1405 | 1 | queue_id = settings.QUEUE_ID if queue_id == -1 else queue_id |
|
1406 | 1 | if queue_id is not None: |
|
1407 | 1 | default_actions.append( |
|
1408 | {"action_type": "set_queue", "queue_id": queue_id} |
||
1409 | ) |
||
1410 | |||
1411 | 1 | flow_mod = { |
|
1412 | "match": {"in_port": in_interface.port_number}, |
||
1413 | "cookie": self.get_cookie(), |
||
1414 | "actions": default_actions, |
||
1415 | "owner": "mef_eline", |
||
1416 | } |
||
1417 | |||
1418 | 1 | self.set_flow_table_group_id(flow_mod, vlan) |
|
1419 | 1 | if self.sb_priority: |
|
1420 | 1 | flow_mod["priority"] = self.sb_priority |
|
1421 | else: |
||
1422 | 1 | flow_mod["priority"] = self.get_priority(vlan) |
|
1423 | 1 | return flow_mod |
|
1424 | |||
1425 | 1 | def _prepare_nni_flow(self, *args, queue_id=None): |
|
1426 | """Create NNI flows.""" |
||
1427 | 1 | in_interface, out_interface, in_vlan, out_vlan = args |
|
1428 | 1 | flow_mod = self._prepare_flow_mod( |
|
1429 | in_interface, out_interface, queue_id |
||
1430 | ) |
||
1431 | 1 | flow_mod["match"]["dl_vlan"] = in_vlan |
|
1432 | 1 | new_action = {"action_type": "set_vlan", "vlan_id": out_vlan} |
|
1433 | 1 | flow_mod["actions"].insert(0, new_action) |
|
1434 | |||
1435 | 1 | return flow_mod |
|
1436 | |||
1437 | 1 | def _prepare_push_flow(self, *args, queue_id=None): |
|
1438 | """Prepare push flow. |
||
1439 | |||
1440 | Arguments: |
||
1441 | in_interface(str): Interface input. |
||
1442 | out_interface(str): Interface output. |
||
1443 | in_vlan(int,str,None): Vlan input. |
||
1444 | out_vlan(str): Vlan output. |
||
1445 | new_c_vlan(int,str,list,None): New client vlan. |
||
1446 | |||
1447 | Return: |
||
1448 | dict: An python dictionary representing a FlowMod |
||
1449 | |||
1450 | """ |
||
1451 | # assign all arguments |
||
1452 | 1 | in_interface, out_interface, in_vlan, out_vlan, new_c_vlan = args |
|
1453 | 1 | vlan_pri = in_vlan if not isinstance(new_c_vlan, list) else new_c_vlan |
|
1454 | 1 | flow_mod = self._prepare_flow_mod( |
|
1455 | in_interface, out_interface, queue_id, vlan_pri |
||
1456 | ) |
||
1457 | # the service tag must be always pushed |
||
1458 | 1 | new_action = {"action_type": "set_vlan", "vlan_id": out_vlan} |
|
1459 | 1 | flow_mod["actions"].insert(0, new_action) |
|
1460 | |||
1461 | 1 | new_action = {"action_type": "push_vlan", "tag_type": "s"} |
|
1462 | 1 | flow_mod["actions"].insert(0, new_action) |
|
1463 | |||
1464 | 1 | if in_vlan is not None: |
|
1465 | # if in_vlan is set, it must be included in the match |
||
1466 | 1 | flow_mod["match"]["dl_vlan"] = in_vlan |
|
1467 | |||
1468 | 1 | if (not isinstance(new_c_vlan, list) and in_vlan != new_c_vlan and |
|
1469 | new_c_vlan not in self.special_cases): |
||
1470 | # new_in_vlan is an integer but zero, action to set is required |
||
1471 | 1 | new_action = {"action_type": "set_vlan", "vlan_id": new_c_vlan} |
|
1472 | 1 | flow_mod["actions"].insert(0, new_action) |
|
1473 | |||
1474 | 1 | if in_vlan not in self.special_cases and new_c_vlan == 0: |
|
1475 | # # new_in_vlan is an integer but zero and new_c_vlan does not |
||
1476 | # a pop action is required |
||
1477 | 1 | new_action = {"action_type": "pop_vlan"} |
|
1478 | 1 | flow_mod["actions"].insert(0, new_action) |
|
1479 | |||
1480 | 1 | elif in_vlan == "4096/4096" and new_c_vlan == 0: |
|
1481 | # if in_vlan match with any tags and new_c_vlan does not |
||
1482 | # a pop action is required |
||
1483 | 1 | new_action = {"action_type": "pop_vlan"} |
|
1484 | 1 | flow_mod["actions"].insert(0, new_action) |
|
1485 | |||
1486 | 1 | elif (not in_vlan and |
|
1487 | (not isinstance(new_c_vlan, list) and |
||
1488 | new_c_vlan not in self.special_cases)): |
||
1489 | # new_in_vlan is an integer but zero and in_vlan is not set |
||
1490 | # then it is set now |
||
1491 | 1 | new_action = {"action_type": "push_vlan", "tag_type": "c"} |
|
1492 | 1 | flow_mod["actions"].insert(0, new_action) |
|
1493 | |||
1494 | 1 | return flow_mod |
|
1495 | |||
1496 | 1 | def _prepare_pop_flow( |
|
1497 | self, in_interface, out_interface, out_vlan, queue_id=None |
||
1498 | ): |
||
1499 | # pylint: disable=too-many-arguments |
||
1500 | """Prepare pop flow.""" |
||
1501 | 1 | flow_mod = self._prepare_flow_mod( |
|
1502 | in_interface, out_interface, queue_id |
||
1503 | ) |
||
1504 | 1 | flow_mod["match"]["dl_vlan"] = out_vlan |
|
1505 | 1 | new_action = {"action_type": "pop_vlan"} |
|
1506 | 1 | flow_mod["actions"].insert(0, new_action) |
|
1507 | 1 | return flow_mod |
|
1508 | |||
1509 | 1 | @staticmethod |
|
1510 | 1 | def run_bulk_sdntraces( |
|
1511 | uni_list: list[tuple[Interface, Union[str, int, None]]] |
||
1512 | ) -> dict: |
||
1513 | """Run SDN traces on control plane starting from EVC UNIs.""" |
||
1514 | 1 | endpoint = f"{settings.SDN_TRACE_CP_URL}/traces" |
|
1515 | 1 | data = [] |
|
1516 | 1 | for interface, tag_value in uni_list: |
|
1517 | 1 | data_uni = { |
|
1518 | "trace": { |
||
1519 | "switch": { |
||
1520 | "dpid": interface.switch.dpid, |
||
1521 | "in_port": interface.port_number, |
||
1522 | } |
||
1523 | } |
||
1524 | } |
||
1525 | 1 | if tag_value: |
|
1526 | 1 | uni_dl_vlan = map_dl_vlan(tag_value) |
|
1527 | 1 | if uni_dl_vlan: |
|
1528 | 1 | data_uni["trace"]["eth"] = { |
|
1529 | "dl_type": 0x8100, |
||
1530 | "dl_vlan": uni_dl_vlan, |
||
1531 | } |
||
1532 | 1 | data.append(data_uni) |
|
1533 | 1 | try: |
|
1534 | 1 | response = httpx.put(endpoint, json=data, timeout=30) |
|
1535 | 1 | except httpx.TimeoutException as exception: |
|
1536 | 1 | log.error(f"Request has timed out: {exception}") |
|
1537 | 1 | return {"result": []} |
|
1538 | 1 | if response.status_code >= 400: |
|
1539 | 1 | log.error(f"Failed to run sdntrace-cp: {response.text}") |
|
1540 | 1 | return {"result": []} |
|
1541 | 1 | return response.json() |
|
1542 | |||
1543 | # pylint: disable=too-many-return-statements, too-many-arguments |
||
1544 | 1 | @staticmethod |
|
1545 | 1 | def check_trace( |
|
1546 | evc_id: str, |
||
1547 | evc_name: str, |
||
1548 | tag_a: Union[None, int, str], |
||
1549 | tag_z: Union[None, int, str], |
||
1550 | interface_a: Interface, |
||
1551 | interface_z: Interface, |
||
1552 | current_path: list, |
||
1553 | trace_a: list, |
||
1554 | trace_z: list |
||
1555 | ) -> bool: |
||
1556 | """Auxiliar function to check an individual trace""" |
||
1557 | 1 | if ( |
|
1558 | len(trace_a) != len(current_path) + 1 |
||
1559 | or not compare_uni_out_trace(tag_z, interface_z, trace_a[-1]) |
||
1560 | ): |
||
1561 | 1 | log.warning(f"From EVC({evc_id}) named '{evc_name}'. " |
|
1562 | f"Invalid trace from uni_a: {trace_a}") |
||
1563 | 1 | return False |
|
1564 | 1 | if ( |
|
1565 | len(trace_z) != len(current_path) + 1 |
||
1566 | or not compare_uni_out_trace(tag_a, interface_a, trace_z[-1]) |
||
1567 | ): |
||
1568 | 1 | log.warning(f"From EVC({evc_id}) named '{evc_name}'. " |
|
1569 | f"Invalid trace from uni_z: {trace_z}") |
||
1570 | 1 | return False |
|
1571 | |||
1572 | 1 | if not current_path: |
|
1573 | return True |
||
1574 | |||
1575 | 1 | first_link, trace_path_begin, trace_path_end = current_path[0], [], [] |
|
1576 | 1 | if ( |
|
1577 | first_link.endpoint_a.switch.id == trace_a[0]["dpid"] |
||
1578 | ): |
||
1579 | 1 | trace_path_begin, trace_path_end = trace_a, trace_z |
|
1580 | 1 | elif ( |
|
1581 | first_link.endpoint_a.switch.id == trace_z[0]["dpid"] |
||
1582 | ): |
||
1583 | 1 | trace_path_begin, trace_path_end = trace_z, trace_a |
|
1584 | else: |
||
1585 | msg = ( |
||
1586 | f"first link {first_link} endpoint_a didn't match the first " |
||
1587 | f"step of trace_a {trace_a} or trace_z {trace_z}" |
||
1588 | ) |
||
1589 | log.warning(msg) |
||
1590 | return False |
||
1591 | |||
1592 | 1 | for link, trace1, trace2 in zip(current_path, |
|
1593 | trace_path_begin[1:], |
||
1594 | trace_path_end[:0:-1]): |
||
1595 | 1 | metadata_vlan = None |
|
1596 | 1 | if link.metadata: |
|
1597 | 1 | metadata_vlan = glom(link.metadata, 's_vlan.value') |
|
1598 | 1 | if compare_endpoint_trace( |
|
1599 | link.endpoint_a, |
||
1600 | metadata_vlan, |
||
1601 | trace2 |
||
1602 | ) is False: |
||
1603 | 1 | log.warning(f"From EVC({evc_id}) named '{evc_name}'. " |
|
1604 | f"Invalid trace from uni_a: {trace_a}") |
||
1605 | 1 | return False |
|
1606 | 1 | if compare_endpoint_trace( |
|
1607 | link.endpoint_b, |
||
1608 | metadata_vlan, |
||
1609 | trace1 |
||
1610 | ) is False: |
||
1611 | 1 | log.warning(f"From EVC({evc_id}) named '{evc_name}'. " |
|
1612 | f"Invalid trace from uni_z: {trace_z}") |
||
1613 | 1 | return False |
|
1614 | |||
1615 | 1 | return True |
|
1616 | |||
1617 | 1 | @staticmethod |
|
1618 | 1 | def check_range(circuit, traces: list) -> bool: |
|
1619 | """Check traces when for UNI with TAGRange""" |
||
1620 | 1 | check = True |
|
1621 | 1 | for i, mask in enumerate(circuit.uni_a.user_tag.mask_list): |
|
1622 | 1 | trace_a = traces[i*2] |
|
1623 | 1 | trace_z = traces[i*2+1] |
|
1624 | 1 | check &= EVCDeploy.check_trace( |
|
1625 | circuit.id, circuit.name, |
||
1626 | mask, mask, |
||
1627 | circuit.uni_a.interface, |
||
1628 | circuit.uni_z.interface, |
||
1629 | circuit.current_path, |
||
1630 | trace_a, trace_z, |
||
1631 | ) |
||
1632 | 1 | return check |
|
1633 | |||
1634 | 1 | @staticmethod |
|
1635 | 1 | def check_list_traces(list_circuits: list) -> dict: |
|
1636 | """Check if current_path is deployed comparing with SDN traces.""" |
||
1637 | 1 | if not list_circuits: |
|
1638 | 1 | return {} |
|
1639 | 1 | uni_list = make_uni_list(list_circuits) |
|
1640 | 1 | traces = EVCDeploy.run_bulk_sdntraces(uni_list)["result"] |
|
1641 | |||
1642 | 1 | if not traces: |
|
1643 | 1 | return {} |
|
1644 | |||
1645 | 1 | try: |
|
1646 | 1 | circuits_checked = {} |
|
1647 | 1 | i = 0 |
|
1648 | 1 | for circuit in list_circuits: |
|
1649 | 1 | if isinstance(circuit.uni_a.user_tag, TAGRange): |
|
1650 | 1 | length = len(circuit.uni_a.user_tag.mask_list) |
|
1651 | 1 | circuits_checked[circuit.id] = EVCDeploy.check_range( |
|
1652 | circuit, traces[i:i+length*2] |
||
1653 | ) |
||
1654 | 1 | i += length*2 |
|
1655 | else: |
||
1656 | 1 | trace_a = traces[i] |
|
1657 | 1 | trace_z = traces[i+1] |
|
1658 | 1 | tag_a = None |
|
1659 | 1 | if circuit.uni_a.user_tag: |
|
1660 | 1 | tag_a = circuit.uni_a.user_tag.value |
|
1661 | 1 | tag_z = None |
|
1662 | 1 | if circuit.uni_z.user_tag: |
|
1663 | 1 | tag_z = circuit.uni_z.user_tag.value |
|
1664 | 1 | circuits_checked[circuit.id] = EVCDeploy.check_trace( |
|
1665 | circuit.id, circuit.name, |
||
1666 | tag_a, tag_z, |
||
1667 | circuit.uni_a.interface, |
||
1668 | circuit.uni_z.interface, |
||
1669 | circuit.current_path, |
||
1670 | trace_a, trace_z |
||
1671 | ) |
||
1672 | 1 | i += 2 |
|
1673 | 1 | except IndexError as err: |
|
1674 | 1 | log.error( |
|
1675 | f"Bulk sdntraces returned fewer items than expected." |
||
1676 | f"Error = {err}" |
||
1677 | ) |
||
1678 | 1 | return {} |
|
1679 | |||
1680 | 1 | return circuits_checked |
|
1681 | |||
1682 | 1 | @staticmethod |
|
1683 | 1 | def get_endpoint_by_id( |
|
1684 | link: Link, |
||
1685 | id_: str, |
||
1686 | operator: Union[eq, ne] |
||
1687 | ) -> Interface: |
||
1688 | """Return endpoint from link |
||
1689 | either equal(eq) or not equal(ne) to id""" |
||
1690 | 1 | if operator(link.endpoint_a.switch.id, id_): |
|
1691 | 1 | return link.endpoint_a |
|
1692 | 1 | return link.endpoint_b |
|
1693 | |||
1694 | |||
1695 | 1 | class LinkProtection(EVCDeploy): |
|
1696 | """Class to handle link protection.""" |
||
1697 | |||
1698 | 1 | def is_affected_by_link(self, link=None): |
|
1699 | """Verify if the current path is affected by link down event.""" |
||
1700 | return self.current_path.is_affected_by_link(link) |
||
1701 | |||
1702 | 1 | def is_using_primary_path(self): |
|
1703 | """Verify if the current deployed path is self.primary_path.""" |
||
1704 | 1 | return self.current_path == self.primary_path |
|
1705 | |||
1706 | 1 | def is_using_backup_path(self): |
|
1707 | """Verify if the current deployed path is self.backup_path.""" |
||
1708 | 1 | return self.current_path == self.backup_path |
|
1709 | |||
1710 | 1 | def is_using_dynamic_path(self): |
|
1711 | """Verify if the current deployed path is dynamic.""" |
||
1712 | 1 | if ( |
|
1713 | self.current_path |
||
1714 | and not self.is_using_primary_path() |
||
1715 | and not self.is_using_backup_path() |
||
1716 | and self.current_path.status is EntityStatus.UP |
||
1717 | ): |
||
1718 | return True |
||
1719 | 1 | return False |
|
1720 | |||
1721 | 1 | def handle_link_up(self, link): |
|
1722 | """Handle circuit when link up. |
||
1723 | |||
1724 | Args: |
||
1725 | link(Link): Link affected by link.up event. |
||
1726 | |||
1727 | """ |
||
1728 | 1 | condition_pairs = [ |
|
1729 | ( |
||
1730 | lambda me: me.is_using_primary_path(), |
||
1731 | lambda _: (True, 'nothing') |
||
1732 | ), |
||
1733 | ( |
||
1734 | lambda me: me.is_intra_switch(), |
||
1735 | lambda _: (True, 'nothing') |
||
1736 | ), |
||
1737 | ( |
||
1738 | lambda me: me.primary_path.is_affected_by_link(link), |
||
1739 | lambda me: (me.deploy_to_primary_path(), 'redeploy') |
||
1740 | ), |
||
1741 | # We tried to deploy(primary_path) without success. |
||
1742 | # And in this case is up by some how. Nothing to do. |
||
1743 | ( |
||
1744 | lambda me: me.is_using_backup_path(), |
||
1745 | lambda _: (True, 'nothing') |
||
1746 | ), |
||
1747 | ( |
||
1748 | lambda me: me.is_using_dynamic_path(), |
||
1749 | lambda _: (True, 'nothing') |
||
1750 | ), |
||
1751 | # In this case, probably the circuit is not being used and |
||
1752 | # we can move to backup |
||
1753 | ( |
||
1754 | lambda me: me.backup_path.is_affected_by_link(link), |
||
1755 | lambda me: (me.deploy_to_backup_path(), 'redeploy') |
||
1756 | ), |
||
1757 | # In this case, the circuit is not being used and we should |
||
1758 | # try a dynamic path |
||
1759 | ( |
||
1760 | lambda me: me.dynamic_backup_path and not me.is_active(), |
||
1761 | lambda me: (me.deploy_to_path(), 'redeploy') |
||
1762 | ) |
||
1763 | ] |
||
1764 | 1 | for predicate, action in condition_pairs: |
|
1765 | 1 | if not predicate(self): |
|
1766 | 1 | continue |
|
1767 | 1 | success, succcess_type = action(self) |
|
1768 | 1 | if success: |
|
1769 | 1 | if succcess_type == 'redeploy': |
|
1770 | 1 | emit_event( |
|
1771 | self._controller, |
||
1772 | "redeployed_link_up", |
||
1773 | content=map_evc_event_content(self) |
||
1774 | ) |
||
1775 | 1 | return True |
|
1776 | 1 | return False |
|
1777 | |||
1778 | 1 | def handle_link_down(self): |
|
1779 | """Handle circuit when link down. |
||
1780 | |||
1781 | Returns: |
||
1782 | bool: True if the re-deploy was successly otherwise False. |
||
1783 | |||
1784 | """ |
||
1785 | 1 | success = False |
|
1786 | 1 | if self.is_using_primary_path(): |
|
1787 | 1 | success = self.deploy_to_backup_path() |
|
1788 | 1 | elif self.is_using_backup_path(): |
|
1789 | 1 | success = self.deploy_to_primary_path() |
|
1790 | |||
1791 | 1 | if not success and self.dynamic_backup_path: |
|
1792 | 1 | success = self.deploy_to_path() |
|
1793 | |||
1794 | 1 | if success: |
|
1795 | 1 | log.debug(f"{self} deployed after link down.") |
|
1796 | else: |
||
1797 | 1 | self.remove_current_flows(sync=False) |
|
1798 | 1 | self.deactivate() |
|
1799 | 1 | self.sync() |
|
1800 | 1 | log.debug(f"Failed to re-deploy {self} after link down.") |
|
1801 | |||
1802 | 1 | return success |
|
1803 | |||
1804 | 1 | @staticmethod |
|
1805 | 1 | def get_interface_from_switch(uni: UNI, switches: dict) -> Interface: |
|
1806 | """Get interface from switch by uni""" |
||
1807 | 1 | switch = switches[uni.interface.switch.dpid] |
|
1808 | 1 | interface = switch.interfaces[uni.interface.port_number] |
|
1809 | 1 | return interface |
|
1810 | |||
1811 | 1 | def are_unis_active(self, switches: dict) -> bool: |
|
1812 | """Determine whether this EVC should be active""" |
||
1813 | 1 | interface_a = self.get_interface_from_switch(self.uni_a, switches) |
|
1814 | 1 | interface_z = self.get_interface_from_switch(self.uni_z, switches) |
|
1815 | 1 | active, _ = self.is_uni_interface_active(interface_a, interface_z) |
|
1816 | 1 | return active |
|
1817 | |||
1818 | 1 | def try_to_handle_uni_as_link_up(self, interface: Interface) -> bool: |
|
1819 | """Try to handle UNI as link_up to trigger deployment.""" |
||
1820 | if ( |
||
1821 | self.current_path.status != EntityStatus.UP |
||
1822 | and not self.is_intra_switch() |
||
1823 | ): |
||
1824 | succeeded = self.handle_link_up(interface) |
||
1825 | if succeeded: |
||
1826 | msg = ( |
||
1827 | f"Activated {self} due to successful " |
||
1828 | f"deployment triggered by {interface}" |
||
1829 | ) |
||
1830 | else: |
||
1831 | msg = ( |
||
1832 | f"Couldn't activate {self} due to unsuccessful " |
||
1833 | f"deployment triggered by {interface}" |
||
1834 | ) |
||
1835 | log.info(msg) |
||
1836 | return True |
||
1837 | return False |
||
1838 | |||
1839 | 1 | def handle_interface_link_up(self, interface: Interface): |
|
1840 | """ |
||
1841 | Handler for interface link_up events |
||
1842 | """ |
||
1843 | 1 | if self.is_active(): |
|
1844 | 1 | return |
|
1845 | 1 | interfaces = (self.uni_a.interface, self.uni_z.interface) |
|
1846 | 1 | if interface not in interfaces: |
|
1847 | return |
||
1848 | 1 | down_interfaces = [ |
|
1849 | interface |
||
1850 | for interface in interfaces |
||
1851 | if interface.status != EntityStatus.UP |
||
1852 | ] |
||
1853 | 1 | if down_interfaces: |
|
1854 | return |
||
1855 | 1 | if self.try_to_handle_uni_as_link_up(interface): |
|
1856 | return |
||
1857 | |||
1858 | 1 | interface_dicts = { |
|
1859 | interface.id: { |
||
1860 | 'status': interface.status.value, |
||
1861 | 'status_reason': interface.status_reason, |
||
1862 | } |
||
1863 | for interface in interfaces |
||
1864 | } |
||
1865 | 1 | try: |
|
1866 | 1 | self.try_to_activate() |
|
1867 | 1 | log.info( |
|
1868 | f"Activating {self}. Interfaces: " |
||
1869 | f"{interface_dicts}." |
||
1870 | ) |
||
1871 | 1 | emit_event(self._controller, "uni_active_updated", |
|
1872 | content=map_evc_event_content(self)) |
||
1873 | 1 | self.sync() |
|
1874 | except ActivationError as exc: |
||
1875 | # On this ctx, no ActivationError isn't expected since the |
||
1876 | # activation pre-requisites states were checked, so handled as err |
||
1877 | log.error(f"ActivationError: {str(exc)} when handling {interface}") |
||
1878 | |||
1879 | 1 | def handle_interface_link_down(self, interface): |
|
1880 | """ |
||
1881 | Handler for interface link_down events |
||
1882 | """ |
||
1883 | 1 | if not self.is_active(): |
|
1884 | 1 | return |
|
1885 | 1 | interfaces = (self.uni_a.interface, self.uni_z.interface) |
|
1886 | 1 | if interface not in interfaces: |
|
1887 | return |
||
1888 | 1 | down_interfaces = [ |
|
1889 | interface |
||
1890 | for interface in interfaces |
||
1891 | if interface.status != EntityStatus.UP |
||
1892 | ] |
||
1893 | 1 | if not down_interfaces: |
|
1894 | return |
||
1895 | 1 | interface_dicts = { |
|
1896 | interface.id: { |
||
1897 | 'status': interface.status.value, |
||
1898 | 'status_reason': interface.status_reason, |
||
1899 | } |
||
1900 | for interface in down_interfaces |
||
1901 | } |
||
1902 | 1 | self.deactivate() |
|
1903 | 1 | log.info( |
|
1904 | f"Deactivating {self}. Interfaces: " |
||
1905 | f"{interface_dicts}." |
||
1906 | ) |
||
1907 | 1 | emit_event(self._controller, "uni_active_updated", |
|
1908 | content=map_evc_event_content(self)) |
||
1909 | 1 | self.sync() |
|
1910 | |||
1911 | |||
1912 | 1 | class EVC(LinkProtection): |
|
1913 | """Class that represents a E-Line Virtual Connection.""" |
||
1914 |