Total Complexity | 169 |
Total Lines | 943 |
Duplicated Lines | 4.98 % |
Coverage | 82.52% |
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 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.""" |
||
2 | 1 | from datetime import datetime |
|
3 | 1 | from threading import Lock |
|
4 | from uuid import uuid4 |
||
5 | 1 | ||
6 | import requests |
||
7 | 1 | ||
8 | 1 | from kytos.core import log |
|
9 | 1 | from kytos.core.common import EntityStatus, GenericEntity |
|
10 | 1 | from kytos.core.exceptions import KytosNoTagAvailableError |
|
11 | 1 | from kytos.core.helpers import get_time, now |
|
12 | 1 | from kytos.core.interface import UNI |
|
13 | 1 | from kytos.core.link import Link |
|
14 | from napps.kytos.mef_eline import settings |
||
15 | from napps.kytos.mef_eline.exceptions import FlowModException |
||
16 | 1 | from napps.kytos.mef_eline.storehouse import StoreHouse |
|
17 | from napps.kytos.mef_eline.utils import emit_event |
||
18 | |||
19 | 1 | ||
20 | class Path(list, GenericEntity): |
||
21 | 1 | """Class to represent a Path.""" |
|
22 | 1 | ||
23 | 1 | def __eq__(self, other=None): |
|
24 | """Compare paths.""" |
||
25 | 1 | if not other or not isinstance(other, Path): |
|
26 | return False |
||
27 | 1 | return super().__eq__(other) |
|
28 | |||
29 | 1 | def is_affected_by_link(self, link=None): |
|
30 | """Verify if the current path is affected by link.""" |
||
31 | 1 | if not link: |
|
32 | return False |
||
33 | return link in self |
||
34 | |||
35 | def link_affected_by_interface(self, interface=None): |
||
36 | """Return the link using this interface, if any, or None otherwise.""" |
||
37 | if not interface: |
||
38 | return None |
||
39 | for link in self: |
||
40 | 1 | if interface in (link.endpoint_a, link.endpoint_b): |
|
41 | return link |
||
42 | 1 | return None |
|
43 | 1 | ||
44 | 1 | def choose_vlans(self): |
|
45 | 1 | """Choose the VLANs to be used for the circuit.""" |
|
46 | for link in self: |
||
47 | 1 | tag = link.get_next_available_tag() |
|
48 | link.use_tag(tag) |
||
49 | 1 | link.add_metadata('s_vlan', tag) |
|
50 | 1 | ||
51 | 1 | def make_vlans_available(self): |
|
52 | """Make the VLANs used in a path available when undeployed.""" |
||
53 | 1 | for link in self: |
|
54 | link.make_tag_available(link.get_metadata('s_vlan')) |
||
55 | link.remove_metadata('s_vlan') |
||
56 | |||
57 | @property |
||
58 | def status(self): |
||
59 | 1 | """Check for the status of a path. |
|
60 | 1 | ||
61 | If any link in this path is down, the path is considered down. |
||
62 | 1 | """ |
|
63 | 1 | if not self: |
|
64 | 1 | return EntityStatus.DISABLED |
|
65 | |||
66 | endpoint = '%s/%s' % (settings.TOPOLOGY_URL, 'links') |
||
67 | api_reply = requests.get(endpoint) |
||
68 | 1 | if api_reply.status_code != getattr(requests.codes, 'ok'): |
|
69 | 1 | log.error('Failed to get links at %s. Returned %s', |
|
70 | 1 | endpoint, api_reply.status_code) |
|
71 | 1 | return None |
|
72 | links = api_reply.json()['links'] |
||
73 | return_status = EntityStatus.UP |
||
74 | 1 | for path_link in self: |
|
75 | 1 | try: |
|
76 | 1 | link = links[path_link.id] |
|
77 | except KeyError: |
||
78 | 1 | return EntityStatus.DISABLED |
|
79 | if link['enabled'] is False: |
||
80 | 1 | return EntityStatus.DISABLED |
|
81 | if link['active'] is False: |
||
82 | return_status = EntityStatus.DOWN |
||
83 | 1 | return return_status |
|
84 | |||
85 | def as_dict(self): |
||
86 | 1 | """Return list comprehension of links as_dict.""" |
|
87 | return [link.as_dict() for link in self if link] |
||
88 | 1 | ||
89 | 1 | ||
90 | class DynamicPathManager: |
||
91 | 1 | """Class to handle and create paths.""" |
|
92 | |||
93 | 1 | controller = None |
|
94 | |||
95 | @classmethod |
||
96 | def set_controller(cls, controller=None): |
||
97 | """Set the controller to discovery news paths.""" |
||
98 | cls.controller = controller |
||
99 | |||
100 | @staticmethod |
||
101 | def get_paths(circuit): |
||
102 | """Get a valid path for the circuit from the Pathfinder.""" |
||
103 | endpoint = settings.PATHFINDER_URL |
||
104 | request_data = {"source": circuit.uni_a.interface.id, |
||
105 | "destination": circuit.uni_z.interface.id} |
||
106 | api_reply = requests.post(endpoint, json=request_data) |
||
107 | |||
108 | 1 | if api_reply.status_code != getattr(requests.codes, 'ok'): |
|
109 | log.error("Failed to get paths at %s. Returned %s", |
||
110 | endpoint, api_reply.status_code) |
||
111 | return None |
||
112 | reply_data = api_reply.json() |
||
113 | 1 | return reply_data.get('paths') |
|
114 | |||
115 | @staticmethod |
||
116 | def _clear_path(path): |
||
117 | """Remove switches from a path, returning only interfaces.""" |
||
118 | return [endpoint for endpoint in path if len(endpoint) > 23] |
||
119 | |||
120 | @classmethod |
||
121 | 1 | def get_best_path(cls, circuit): |
|
122 | """Return the best path available for a circuit, if exists.""" |
||
123 | paths = cls.get_paths(circuit) |
||
124 | if paths: |
||
125 | return cls.create_path(cls.get_paths(circuit)[0]['hops']) |
||
126 | return None |
||
127 | |||
128 | @classmethod |
||
129 | def get_best_paths(cls, circuit): |
||
130 | """Return the best paths available for a circuit, if they exist.""" |
||
131 | for path in cls.get_paths(circuit): |
||
132 | yield cls.create_path(path['hops']) |
||
133 | |||
134 | @classmethod |
||
135 | def create_path(cls, path): |
||
136 | """Return the path containing only the interfaces.""" |
||
137 | new_path = Path() |
||
138 | clean_path = cls._clear_path(path) |
||
139 | |||
140 | 1 | if len(clean_path) % 2: |
|
141 | return None |
||
142 | |||
143 | 1 | for link in zip(clean_path[1:-1:2], clean_path[2::2]): |
|
144 | interface_a = cls.controller.get_interface_by_id(link[0]) |
||
145 | 1 | interface_b = cls.controller.get_interface_by_id(link[1]) |
|
146 | if interface_a is None or interface_b is None: |
||
147 | return None |
||
148 | new_path.append(Link(interface_a, interface_b)) |
||
149 | |||
150 | return new_path |
||
151 | |||
152 | |||
153 | class EVCBase(GenericEntity): |
||
154 | """Class to represent a circuit.""" |
||
155 | |||
156 | read_only_attributes = [ |
||
157 | 'creation_time', 'active', 'current_path', |
||
158 | '_id', 'archived' |
||
159 | ] |
||
160 | required_attributes = ['name', 'uni_a', 'uni_z'] |
||
161 | |||
162 | def __init__(self, controller, **kwargs): |
||
163 | """Create an EVC instance with the provided parameters. |
||
164 | |||
165 | Args: |
||
166 | id(str): EVC identifier. Whether it's None an ID will be genereted. |
||
167 | Only the first 14 bytes passed will be used. |
||
168 | name: represents an EVC name.(Required) |
||
169 | uni_a (UNI): Endpoint A for User Network Interface.(Required) |
||
170 | uni_z (UNI): Endpoint Z for User Network Interface.(Required) |
||
171 | start_date(datetime|str): Date when the EVC was registred. |
||
172 | Default is now(). |
||
173 | end_date(datetime|str): Final date that the EVC will be fineshed. |
||
174 | Default is None. |
||
175 | bandwidth(int): Bandwidth used by EVC instance. Default is 0. |
||
176 | primary_links(list): Primary links used by evc. Default is [] |
||
177 | backup_links(list): Backups links used by evc. Default is [] |
||
178 | current_path(list): Circuit being used at the moment if this is an |
||
179 | active circuit. Default is []. |
||
180 | primary_path(list): primary circuit offered to user IF one or more |
||
181 | 1 | links were provided. Default is []. |
|
182 | 1 | backup_path(list): backup circuit offered to the user IF one or |
|
183 | more links were provided. Default is []. |
||
184 | dynamic_backup_path(bool): Enable computer backup path dynamically. |
||
185 | 1 | Dafault is False. |
|
186 | 1 | creation_time(datetime|str): datetime when the circuit should be |
|
187 | 1 | activated. default is now(). |
|
188 | 1 | enabled(Boolean): attribute to indicate the administrative state; |
|
189 | default is False. |
||
190 | active(Boolean): attribute to indicate the operational state; |
||
191 | 1 | default is False. |
|
192 | 1 | archived(Boolean): indicate the EVC has been deleted and is |
|
193 | archived; default is False. |
||
194 | 1 | owner(str): The EVC owner. Default is None. |
|
195 | 1 | priority(int): Service level provided in the request. Default is 0. |
|
196 | 1 | ||
197 | 1 | Raises: |
|
198 | 1 | ValueError: raised when object attributes are invalid. |
|
199 | 1 | ||
200 | 1 | """ |
|
201 | 1 | self._validate(**kwargs) |
|
202 | 1 | super().__init__() |
|
203 | 1 | ||
204 | 1 | # required attributes |
|
205 | self._id = kwargs.get('id', uuid4().hex)[:14] |
||
206 | 1 | self.uni_a = kwargs.get('uni_a') |
|
207 | 1 | self.uni_z = kwargs.get('uni_z') |
|
208 | 1 | self.name = kwargs.get('name') |
|
209 | |||
210 | 1 | # optional attributes |
|
211 | self.start_date = get_time(kwargs.get('start_date')) or now() |
||
212 | 1 | self.end_date = get_time(kwargs.get('end_date')) or None |
|
213 | 1 | self.queue_id = kwargs.get('queue_id', None) |
|
214 | |||
215 | 1 | self.bandwidth = kwargs.get('bandwidth', 0) |
|
216 | self.primary_links = Path(kwargs.get('primary_links', [])) |
||
217 | 1 | self.backup_links = Path(kwargs.get('backup_links', [])) |
|
218 | 1 | self.current_path = Path(kwargs.get('current_path', [])) |
|
219 | self.primary_path = Path(kwargs.get('primary_path', [])) |
||
220 | 1 | self.backup_path = Path(kwargs.get('backup_path', [])) |
|
221 | self.dynamic_backup_path = kwargs.get('dynamic_backup_path', False) |
||
222 | self.creation_time = get_time(kwargs.get('creation_time')) or now() |
||
223 | self.owner = kwargs.get('owner', None) |
||
224 | 1 | self.priority = kwargs.get('priority', -1) |
|
225 | self.circuit_scheduler = kwargs.get('circuit_scheduler', []) |
||
226 | 1 | ||
227 | self.current_links_cache = set() |
||
228 | 1 | self.primary_links_cache = set() |
|
229 | self.backup_links_cache = set() |
||
230 | 1 | ||
231 | self.lock = Lock() |
||
232 | 1 | ||
233 | self.archived = kwargs.get('archived', False) |
||
234 | |||
235 | self._storehouse = StoreHouse(controller) |
||
236 | self._controller = controller |
||
237 | |||
238 | if kwargs.get('active', False): |
||
239 | self.activate() |
||
240 | else: |
||
241 | self.deactivate() |
||
242 | 1 | ||
243 | 1 | if kwargs.get('enabled', False): |
|
244 | 1 | self.enable() |
|
245 | else: |
||
246 | self.disable() |
||
247 | |||
248 | # datetime of user request for a EVC (or datetime when object was |
||
249 | # created) |
||
250 | self.request_time = kwargs.get('request_time', now()) |
||
251 | 1 | # dict with the user original request (input) |
|
252 | self._requested = kwargs |
||
253 | 1 | ||
254 | def sync(self): |
||
255 | 1 | """Sync this EVC in the storehouse.""" |
|
256 | self._storehouse.save_evc(self) |
||
257 | log.info(f'EVC {self.id} was synced to the storehouse.') |
||
258 | |||
259 | def update(self, **kwargs): |
||
260 | """Update evc attributes. |
||
261 | |||
262 | This method will raises an error trying to change the following |
||
263 | attributes: [name, uni_a and uni_z] |
||
264 | |||
265 | 1 | Returns: |
|
266 | the values for enable and a redeploy attribute, if exists and None |
||
267 | 1 | otherwise |
|
268 | 1 | Raises: |
|
269 | ValueError: message with error detail. |
||
270 | 1 | ||
271 | 1 | """ |
|
272 | 1 | enable, redeploy = (None, None) |
|
273 | for attribute, value in kwargs.items(): |
||
274 | if attribute in self.read_only_attributes: |
||
275 | 1 | raise ValueError(f'{attribute} can\'t be updated.') |
|
276 | 1 | if hasattr(self, attribute): |
|
277 | 1 | if attribute in ('enable', 'enabled'): |
|
278 | 1 | if value: |
|
279 | self.enable() |
||
280 | 1 | else: |
|
281 | self.disable() |
||
282 | 1 | enable = value |
|
283 | else: |
||
284 | setattr(self, attribute, value) |
||
285 | 1 | if 'path' in attribute or 'priority' in attribute: |
|
286 | 1 | redeploy = value |
|
287 | 1 | else: |
|
288 | 1 | raise ValueError(f'The attribute "{attribute}" is invalid.') |
|
289 | 1 | self.sync() |
|
290 | return enable, redeploy |
||
291 | 1 | ||
292 | def __repr__(self): |
||
293 | 1 | """Repr method.""" |
|
294 | return f"EVC({self._id}, {self.name})" |
||
295 | |||
296 | def _validate(self, **kwargs): |
||
297 | 1 | """Do Basic validations. |
|
298 | |||
299 | 1 | Verify required attributes: name, uni_a, uni_z |
|
300 | 1 | Verify if the attributes uni_a and uni_z are valid. |
|
301 | 1 | ||
302 | Raises: |
||
303 | 1 | ValueError: message with error detail. |
|
304 | 1 | ||
305 | 1 | """ |
|
306 | for attribute in self.required_attributes: |
||
307 | 1 | ||
308 | 1 | if attribute not in kwargs: |
|
309 | 1 | raise ValueError(f'{attribute} is required.') |
|
310 | 1 | ||
311 | 1 | if 'uni' in attribute: |
|
312 | 1 | uni = kwargs.get(attribute) |
|
313 | 1 | if not isinstance(uni, UNI): |
|
314 | raise ValueError(f'{attribute} is an invalid UNI.') |
||
315 | |||
316 | if not uni.is_valid(): |
||
317 | tag = uni.user_tag.value |
||
318 | message = f'VLAN tag {tag} is not available in {attribute}' |
||
319 | raise ValueError(message) |
||
320 | |||
321 | def __eq__(self, other): |
||
322 | 1 | """Override the default implementation.""" |
|
323 | 1 | if not isinstance(other, EVC): |
|
324 | 1 | return False |
|
325 | |||
326 | 1 | attrs_to_compare = ['name', 'uni_a', 'uni_z', 'owner', 'bandwidth'] |
|
327 | 1 | for attribute in attrs_to_compare: |
|
328 | if getattr(other, attribute) != getattr(self, attribute): |
||
329 | 1 | return False |
|
330 | 1 | return True |
|
331 | |||
332 | def shares_uni(self, other): |
||
333 | 1 | """Check if two EVCs share an UNI.""" |
|
334 | 1 | if other.uni_a in (self.uni_a, self.uni_z) or \ |
|
335 | 1 | other.uni_z in (self.uni_a, self.uni_z): |
|
336 | return True |
||
337 | 1 | return False |
|
338 | |||
339 | 1 | def as_dict(self): |
|
340 | """Return a dictionary representing an EVC object.""" |
||
341 | evc_dict = {"id": self.id, "name": self.name, |
||
342 | 1 | "uni_a": self.uni_a.as_dict(), |
|
343 | "uni_z": self.uni_z.as_dict()} |
||
344 | |||
345 | time_fmt = "%Y-%m-%dT%H:%M:%S" |
||
346 | 1 | ||
347 | evc_dict["start_date"] = self.start_date |
||
348 | if isinstance(self.start_date, datetime): |
||
349 | 1 | evc_dict["start_date"] = self.start_date.strftime(time_fmt) |
|
350 | |||
351 | evc_dict["end_date"] = self.end_date |
||
352 | 1 | if isinstance(self.end_date, datetime): |
|
353 | evc_dict["end_date"] = self.end_date.strftime(time_fmt) |
||
354 | 1 | ||
355 | evc_dict['queue_id'] = self.queue_id |
||
356 | 1 | evc_dict['bandwidth'] = self.bandwidth |
|
357 | evc_dict['primary_links'] = self.primary_links.as_dict() |
||
358 | evc_dict['backup_links'] = self.backup_links.as_dict() |
||
359 | 1 | evc_dict['current_path'] = self.current_path.as_dict() |
|
360 | evc_dict['primary_path'] = self.primary_path.as_dict() |
||
361 | evc_dict['backup_path'] = self.backup_path.as_dict() |
||
362 | 1 | evc_dict['dynamic_backup_path'] = self.dynamic_backup_path |
|
363 | |||
364 | # if self._requested: |
||
365 | # request_dict = self._requested.copy() |
||
366 | 1 | # request_dict['uni_a'] = request_dict['uni_a'].as_dict() |
|
367 | # request_dict['uni_z'] = request_dict['uni_z'].as_dict() |
||
368 | # request_dict['circuit_scheduler'] = self.circuit_scheduler |
||
369 | # evc_dict['_requested'] = request_dict |
||
370 | 1 | ||
371 | evc_dict["request_time"] = self.request_time |
||
372 | if isinstance(self.request_time, datetime): |
||
373 | evc_dict["request_time"] = self.request_time.strftime(time_fmt) |
||
374 | |||
375 | 1 | time = self.creation_time.strftime(time_fmt) |
|
376 | evc_dict['creation_time'] = time |
||
377 | |||
378 | evc_dict['owner'] = self.owner |
||
379 | 1 | evc_dict['circuit_scheduler'] = [sc.as_dict() |
|
380 | for sc in self.circuit_scheduler] |
||
381 | |||
382 | evc_dict['active'] = self.is_active() |
||
383 | 1 | evc_dict['enabled'] = self.is_enabled() |
|
384 | evc_dict['archived'] = self.archived |
||
385 | evc_dict['priority'] = self.priority |
||
386 | |||
387 | 1 | return evc_dict |
|
388 | |||
389 | @property |
||
390 | def id(self): # pylint: disable=invalid-name |
||
391 | """Return this EVC's ID.""" |
||
392 | return self._id |
||
393 | |||
394 | def archive(self): |
||
395 | """Archive this EVC on deletion.""" |
||
396 | 1 | self.archived = True |
|
397 | |||
398 | |||
399 | # pylint: disable=fixme, too-many-public-methods |
||
400 | class EVCDeploy(EVCBase): |
||
401 | """Class to handle the deploy procedures.""" |
||
402 | |||
403 | def create(self): |
||
404 | """Create a EVC.""" |
||
405 | |||
406 | 1 | def discover_new_paths(self): |
|
407 | """Discover new paths to satisfy this circuit and deploy it.""" |
||
408 | return DynamicPathManager.get_best_paths(self) |
||
409 | |||
410 | 1 | def change_path(self): |
|
411 | 1 | """Change EVC path.""" |
|
412 | 1 | ||
413 | def reprovision(self): |
||
414 | 1 | """Force the EVC (re-)provisioning.""" |
|
415 | 1 | ||
416 | def is_affected_by_link(self, link): |
||
417 | 1 | """Return True if this EVC has the given link on its current path.""" |
|
418 | 1 | return link in self.current_path |
|
419 | |||
420 | 1 | def link_affected_by_interface(self, interface): |
|
421 | """Return True if this EVC has the given link on its current path.""" |
||
422 | 1 | return self.current_path.link_affected_by_interface(interface) |
|
423 | |||
424 | def is_backup_path_affected_by_link(self, link): |
||
425 | """Return True if the backup path of this EVC uses the given link.""" |
||
426 | return link in self.backup_path |
||
427 | |||
428 | # pylint: disable=invalid-name |
||
429 | 1 | def is_primary_path_affected_by_link(self, link): |
|
430 | """Return True if the primary path of this EVC uses the given link.""" |
||
431 | return link in self.primary_path |
||
432 | |||
433 | 1 | def is_using_primary_path(self): |
|
434 | 1 | """Verify if the current deployed path is self.primary_path.""" |
|
435 | 1 | return self.primary_path and (self.current_path == self.primary_path) |
|
436 | |||
437 | 1 | def is_using_backup_path(self): |
|
438 | """Verify if the current deployed path is self.backup_path.""" |
||
439 | return self.backup_path and (self.current_path == self.backup_path) |
||
440 | |||
441 | def is_using_dynamic_path(self): |
||
442 | """Verify if the current deployed path is a dynamic path.""" |
||
443 | 1 | if self.current_path and \ |
|
444 | 1 | not self.is_using_primary_path() and \ |
|
445 | 1 | not self.is_using_backup_path() and \ |
|
446 | 1 | self.current_path.status == EntityStatus.UP: |
|
447 | return True |
||
448 | 1 | return False |
|
449 | |||
450 | 1 | def deploy_to_backup_path(self): |
|
451 | """Deploy the backup path into the datapaths of this circuit. |
||
452 | |||
453 | If the backup_path attribute is valid and up, this method will try to |
||
454 | deploy this backup_path. |
||
455 | |||
456 | If everything fails and dynamic_backup_path is True, then tries to |
||
457 | deploy a dynamic path. |
||
458 | """ |
||
459 | # TODO: Remove flows from current (cookies) |
||
460 | if self.is_using_backup_path(): |
||
461 | # TODO: Log to say that cannot move backup to backup |
||
462 | return True |
||
463 | |||
464 | success = False |
||
465 | if self.backup_path.status is EntityStatus.UP: |
||
466 | success = self.deploy_to_path(self.backup_path) |
||
467 | 1 | ||
468 | if success: |
||
469 | return True |
||
470 | |||
471 | 1 | if self.dynamic_backup_path or \ |
|
472 | self.uni_a.interface.switch == self.uni_z.interface.switch: |
||
473 | 1 | return self.deploy_to_path() |
|
474 | |||
475 | 1 | return False |
|
476 | 1 | ||
477 | 1 | def deploy_to_primary_path(self): |
|
478 | """Deploy the primary path into the datapaths of this circuit. |
||
479 | 1 | ||
480 | If the primary_path attribute is valid and up, this method will try to |
||
481 | deploy this primary_path. |
||
482 | 1 | """ |
|
483 | 1 | # TODO: Remove flows from current (cookies) |
|
484 | if self.is_using_primary_path(): |
||
485 | 1 | # TODO: Log to say that cannot move primary to primary |
|
486 | 1 | return True |
|
487 | 1 | ||
488 | 1 | if self.primary_path.status is EntityStatus.UP: |
|
489 | return self.deploy_to_path(self.primary_path) |
||
490 | 1 | return False |
|
491 | 1 | ||
492 | def deploy(self): |
||
493 | 1 | """Deploy EVC to best path. |
|
494 | |||
495 | 1 | Best path can be the primary path, if available. If not, the backup |
|
496 | path, and, if it is also not available, a dynamic path. |
||
497 | 1 | """ |
|
498 | if self.archived: |
||
499 | 1 | return False |
|
500 | 1 | self.enable() |
|
501 | 1 | success = self.deploy_to_primary_path() |
|
502 | if not success: |
||
503 | 1 | success = self.deploy_to_backup_path() |
|
504 | 1 | ||
505 | 1 | if success: |
|
506 | emit_event(self._controller, 'deployed', evc_id=self.id) |
||
507 | 1 | return success |
|
508 | 1 | ||
509 | 1 | @staticmethod |
|
510 | def get_path_status(path): |
||
511 | 1 | """Check for the current status of a path. |
|
512 | |||
513 | 1 | If any link in this path is down, the path is considered down. |
|
514 | """ |
||
515 | if not path: |
||
516 | return EntityStatus.DISABLED |
||
517 | |||
518 | for link in path: |
||
519 | if link.status is not EntityStatus.UP: |
||
520 | return link.status |
||
521 | return EntityStatus.UP |
||
522 | |||
523 | # def discover_new_path(self): |
||
524 | # # TODO: discover a new path to satisfy this circuit and deploy |
||
525 | |||
526 | def remove(self): |
||
527 | """Remove EVC path and disable it.""" |
||
528 | 1 | self.remove_current_flows() |
|
529 | 1 | self.disable() |
|
530 | 1 | self.sync() |
|
531 | 1 | emit_event(self._controller, 'undeployed', evc_id=self.id) |
|
532 | 1 | ||
533 | def remove_current_flows(self, current_path=None): |
||
534 | 1 | """Remove all flows from current path.""" |
|
535 | 1 | switches = set() |
|
536 | 1 | ||
537 | 1 | switches.add(self.uni_a.interface.switch) |
|
538 | 1 | switches.add(self.uni_z.interface.switch) |
|
539 | 1 | if not current_path: |
|
540 | 1 | current_path = self.current_path |
|
541 | 1 | for link in current_path: |
|
542 | switches.add(link.endpoint_a.switch) |
||
543 | 1 | switches.add(link.endpoint_b.switch) |
|
544 | |||
545 | 1 | match = {'cookie': self.get_cookie(), |
|
546 | 1 | 'cookie_mask': 18446744073709551615} |
|
547 | 1 | ||
548 | for switch in switches: |
||
549 | 1 | self._send_flow_mods(switch, [match], 'delete') |
|
550 | |||
551 | 1 | current_path.make_vlans_available() |
|
552 | self.current_path = Path([]) |
||
553 | self.deactivate() |
||
554 | self.sync() |
||
555 | |||
556 | 1 | @staticmethod |
|
557 | def links_zipped(path=None): |
||
558 | """Return an iterator which yields pairs of links in order.""" |
||
559 | 1 | if not path: |
|
560 | return [] |
||
561 | 1 | return zip(path[:-1], path[1:]) |
|
562 | |||
563 | 1 | def should_deploy(self, path=None): |
|
564 | """Verify if the circuit should be deployed.""" |
||
565 | if not path: |
||
566 | log.debug("Path is empty.") |
||
567 | return False |
||
568 | 1 | ||
569 | 1 | if not self.is_enabled(): |
|
570 | log.debug(f'{self} is disabled.') |
||
571 | 1 | return False |
|
572 | 1 | ||
573 | if not self.is_active(): |
||
574 | log.debug(f'{self} will be deployed.') |
||
575 | 1 | return True |
|
576 | |||
577 | return False |
||
578 | 1 | ||
579 | def deploy_to_path(self, path=None): |
||
580 | """Install the flows for this circuit. |
||
581 | 1 | ||
582 | Procedures to deploy: |
||
583 | |||
584 | 1 | 0. Remove current flows installed |
|
585 | 1. Decide if will deploy "path" or discover a new path |
||
586 | 1 | 2. Choose vlan |
|
587 | 3. Install NNI flows |
||
588 | 1 | 4. Install UNI flows |
|
589 | 5. Activate |
||
590 | 6. Update current_path |
||
591 | 1 | 7. Update links caches(primary, current, backup) |
|
592 | |||
593 | """ |
||
594 | 1 | self.remove_current_flows() |
|
595 | use_path = path |
||
596 | if self.should_deploy(use_path): |
||
597 | 1 | try: |
|
598 | use_path.choose_vlans() |
||
599 | except KytosNoTagAvailableError: |
||
600 | 1 | use_path = None |
|
601 | else: |
||
602 | 1 | for use_path in self.discover_new_paths(): |
|
603 | if use_path is None: |
||
604 | 1 | continue |
|
605 | try: |
||
606 | 1 | use_path.choose_vlans() |
|
607 | 1 | break |
|
608 | except KytosNoTagAvailableError: |
||
609 | pass |
||
610 | else: |
||
611 | use_path = None |
||
612 | |||
613 | try: |
||
614 | if use_path: |
||
615 | self._install_nni_flows(use_path) |
||
616 | 1 | self._install_uni_flows(use_path) |
|
617 | elif self.uni_a.interface.switch == self.uni_z.interface.switch: |
||
618 | 1 | use_path = Path() |
|
619 | 1 | self._install_direct_uni_flows() |
|
620 | else: |
||
621 | 1 | log.warn(f"{self} was not deployed. " |
|
622 | "No available path was found.") |
||
623 | 1 | return False |
|
624 | 1 | except FlowModException: |
|
625 | log.error(f'Error deploying EVC {self} when calling flow_manager.') |
||
626 | 1 | self.remove_current_flows(use_path) |
|
627 | return False |
||
628 | 1 | self.activate() |
|
629 | self.current_path = use_path |
||
630 | self.sync() |
||
631 | 1 | log.info(f"{self} was deployed.") |
|
632 | return True |
||
633 | |||
634 | def _install_direct_uni_flows(self): |
||
635 | 1 | """Install flows connecting two UNIs. |
|
636 | |||
637 | 1 | This case happens when the circuit is between UNIs in the |
|
638 | same switch. |
||
639 | """ |
||
640 | 1 | vlan_a = self.uni_a.user_tag.value if self.uni_a.user_tag else None |
|
641 | 1 | vlan_z = self.uni_z.user_tag.value if self.uni_z.user_tag else None |
|
642 | |||
643 | 1 | flow_mod_az = self._prepare_flow_mod(self.uni_a.interface, |
|
644 | self.uni_z.interface, |
||
645 | 1 | self.queue_id) |
|
646 | flow_mod_za = self._prepare_flow_mod(self.uni_z.interface, |
||
647 | 1 | self.uni_a.interface, |
|
648 | self.queue_id) |
||
649 | 1 | ||
650 | if vlan_a and vlan_z: |
||
651 | flow_mod_az['match']['dl_vlan'] = vlan_a |
||
652 | flow_mod_za['match']['dl_vlan'] = vlan_z |
||
653 | flow_mod_az['actions'].insert(0, {'action_type': 'set_vlan', |
||
654 | 'vlan_id': vlan_z}) |
||
655 | flow_mod_za['actions'].insert(0, {'action_type': 'set_vlan', |
||
656 | 'vlan_id': vlan_a}) |
||
657 | elif vlan_a: |
||
658 | flow_mod_az['match']['dl_vlan'] = vlan_a |
||
659 | flow_mod_az['actions'].insert(0, {'action_type': 'pop_vlan'}) |
||
660 | flow_mod_za['actions'].insert(0, {'action_type': 'set_vlan', |
||
661 | 'vlan_id': vlan_a}) |
||
662 | elif vlan_z: |
||
663 | flow_mod_za['match']['dl_vlan'] = vlan_z |
||
664 | 1 | flow_mod_za['actions'].insert(0, {'action_type': 'pop_vlan'}) |
|
665 | flow_mod_az['actions'].insert(0, {'action_type': 'set_vlan', |
||
666 | 1 | 'vlan_id': vlan_z}) |
|
667 | 1 | self._send_flow_mods(self.uni_a.interface.switch, |
|
668 | [flow_mod_az, flow_mod_za]) |
||
669 | 1 | ||
670 | def _install_nni_flows(self, path=None): |
||
671 | 1 | """Install NNI flows.""" |
|
672 | for incoming, outcoming in self.links_zipped(path): |
||
673 | 1 | in_vlan = incoming.get_metadata('s_vlan').value |
|
674 | out_vlan = outcoming.get_metadata('s_vlan').value |
||
675 | 1 | ||
676 | flows = [] |
||
677 | 1 | # Flow for one direction |
|
678 | flows.append(self._prepare_nni_flow(incoming.endpoint_b, |
||
679 | 1 | outcoming.endpoint_a, |
|
680 | in_vlan, out_vlan, |
||
681 | 1 | queue_id=self.queue_id)) |
|
682 | |||
683 | 1 | # Flow for the other direction |
|
684 | flows.append(self._prepare_nni_flow(outcoming.endpoint_a, |
||
685 | 1 | incoming.endpoint_b, |
|
686 | 1 | out_vlan, in_vlan, |
|
687 | 1 | queue_id=self.queue_id)) |
|
688 | 1 | self._send_flow_mods(incoming.endpoint_b.switch, flows) |
|
689 | 1 | ||
690 | def _install_uni_flows(self, path=None): |
||
691 | """Install UNI flows.""" |
||
692 | 1 | if not path: |
|
693 | log.info('install uni flows without path.') |
||
694 | return |
||
695 | 1 | ||
696 | # Determine VLANs |
||
697 | in_vlan_a = self.uni_a.user_tag.value if self.uni_a.user_tag else None |
||
698 | out_vlan_a = path[0].get_metadata('s_vlan').value |
||
699 | 1 | ||
700 | in_vlan_z = self.uni_z.user_tag.value if self.uni_z.user_tag else None |
||
701 | 1 | out_vlan_z = path[-1].get_metadata('s_vlan').value |
|
702 | |||
703 | 1 | # Flows for the first UNI |
|
704 | flows_a = [] |
||
705 | 1 | ||
706 | # Flow for one direction, pushing the service tag |
||
707 | 1 | push_flow = self._prepare_push_flow(self.uni_a.interface, |
|
708 | path[0].endpoint_a, |
||
709 | 1 | in_vlan_a, out_vlan_a, |
|
710 | queue_id=self.queue_id) |
||
711 | flows_a.append(push_flow) |
||
712 | |||
713 | # Flow for the other direction, popping the service tag |
||
714 | 1 | pop_flow = self._prepare_pop_flow(path[0].endpoint_a, |
|
715 | self.uni_a.interface, |
||
716 | 1 | in_vlan_a, out_vlan_a, |
|
717 | queue_id=self.queue_id) |
||
718 | 1 | flows_a.append(pop_flow) |
|
719 | 1 | ||
720 | 1 | self._send_flow_mods(self.uni_a.interface.switch, flows_a) |
|
721 | |||
722 | 1 | # Flows for the second UNI |
|
723 | 1 | flows_z = [] |
|
724 | |||
725 | 1 | # Flow for one direction, pushing the service tag |
|
726 | push_flow = self._prepare_push_flow(self.uni_z.interface, |
||
727 | 1 | path[-1].endpoint_b, |
|
728 | in_vlan_z, out_vlan_z, |
||
729 | queue_id=self.queue_id) |
||
730 | flows_z.append(push_flow) |
||
731 | |||
732 | # Flow for the other direction, popping the service tag |
||
733 | pop_flow = self._prepare_pop_flow(path[-1].endpoint_b, |
||
734 | 1 | self.uni_z.interface, |
|
735 | 1 | in_vlan_z, out_vlan_z, |
|
736 | queue_id=self.queue_id) |
||
737 | 1 | flows_z.append(pop_flow) |
|
738 | 1 | ||
739 | 1 | self._send_flow_mods(self.uni_z.interface.switch, flows_z) |
|
740 | |||
741 | 1 | @staticmethod |
|
742 | 1 | def _send_flow_mods(switch, flow_mods, command='flows'): |
|
743 | """Send a flow_mod list to a specific switch. |
||
744 | |||
745 | Args: |
||
746 | 1 | switch(Switch): The target of flows. |
|
747 | flow_mods(dict): Python dictionary with flow_mods. |
||
748 | command(str): By default is 'flows'. To remove a flow is 'remove'. |
||
749 | |||
750 | """ |
||
751 | 1 | endpoint = f'{settings.MANAGER_URL}/{command}/{switch.id}' |
|
752 | 1 | ||
753 | data = {"flows": flow_mods} |
||
754 | 1 | response = requests.post(endpoint, json=data) |
|
755 | 1 | if response.status_code >= 400: |
|
756 | raise FlowModException |
||
757 | |||
758 | def get_cookie(self): |
||
759 | """Return the cookie integer from evc id.""" |
||
760 | return int(self.id, 16) + (settings.COOKIE_PREFIX << 56) |
||
761 | |||
762 | def _prepare_flow_mod(self, in_interface, out_interface, queue_id=None): |
||
763 | """Prepare a common flow mod.""" |
||
764 | 1 | default_actions = [{"action_type": "output", |
|
765 | "port": out_interface.port_number}] |
||
766 | if queue_id: |
||
767 | default_actions.append( |
||
768 | {"action_type": "set_queue", "queue_id": queue_id} |
||
769 | ) |
||
770 | |||
771 | 1 | flow_mod = {"match": {"in_port": in_interface.port_number}, |
|
772 | 1 | "cookie": self.get_cookie(), |
|
773 | 1 | "actions": default_actions} |
|
774 | 1 | if self.priority > -1: |
|
775 | 1 | flow_mod['priority'] = self.priority |
|
776 | |||
777 | 1 | return flow_mod |
|
778 | 1 | ||
779 | def _prepare_nni_flow(self, *args, queue_id=None): |
||
780 | 1 | """Create NNI flows.""" |
|
781 | 1 | in_interface, out_interface, in_vlan, out_vlan = args |
|
782 | flow_mod = self._prepare_flow_mod(in_interface, out_interface, |
||
783 | 1 | queue_id) |
|
784 | flow_mod['match']['dl_vlan'] = in_vlan |
||
785 | 1 | ||
786 | new_action = {"action_type": "set_vlan", |
||
787 | "vlan_id": out_vlan} |
||
788 | 1 | flow_mod["actions"].insert(0, new_action) |
|
789 | |||
790 | return flow_mod |
||
791 | |||
792 | View Code Duplication | def _prepare_push_flow(self, *args, queue_id=None): |
|
|
|||
793 | """Prepare push flow. |
||
794 | |||
795 | Arguments: |
||
796 | in_interface(str): Interface input. |
||
797 | out_interface(str): Interface output. |
||
798 | in_vlan(str): Vlan input. |
||
799 | out_vlan(str): Vlan output. |
||
800 | |||
801 | Return: |
||
802 | dict: An python dictionary representing a FlowMod |
||
803 | |||
804 | """ |
||
805 | # assign all arguments |
||
806 | in_interface, out_interface, in_vlan, out_vlan = args |
||
807 | |||
808 | flow_mod = self._prepare_flow_mod(in_interface, out_interface, |
||
809 | queue_id) |
||
810 | |||
811 | # the service tag must be always pushed |
||
812 | new_action = {"action_type": "set_vlan", "vlan_id": out_vlan} |
||
813 | flow_mod["actions"].insert(0, new_action) |
||
814 | |||
815 | new_action = {"action_type": "push_vlan", "tag_type": "s"} |
||
816 | flow_mod["actions"].insert(0, new_action) |
||
817 | |||
818 | if in_vlan: |
||
819 | # if in_vlan is set, it must be included in the match |
||
820 | flow_mod['match']['dl_vlan'] = in_vlan |
||
821 | new_action = {"action_type": "pop_vlan"} |
||
822 | flow_mod["actions"].insert(0, new_action) |
||
823 | return flow_mod |
||
824 | |||
825 | View Code Duplication | def _prepare_pop_flow(self, in_interface, out_interface, in_vlan, |
|
826 | out_vlan, queue_id=None): |
||
827 | # pylint: disable=too-many-arguments |
||
828 | """Prepare pop flow.""" |
||
829 | flow_mod = self._prepare_flow_mod(in_interface, out_interface, |
||
830 | queue_id) |
||
831 | flow_mod['match']['dl_vlan'] = out_vlan |
||
832 | if in_vlan: |
||
833 | new_action = {'action_type': 'set_vlan', 'vlan_id': in_vlan} |
||
834 | flow_mod['actions'].insert(0, new_action) |
||
835 | new_action = {'action_type': 'push_vlan', 'tag_type': 'c'} |
||
836 | flow_mod['actions'].insert(0, new_action) |
||
837 | new_action = {"action_type": "pop_vlan"} |
||
838 | flow_mod["actions"].insert(0, new_action) |
||
839 | return flow_mod |
||
840 | |||
841 | |||
842 | class LinkProtection(EVCDeploy): |
||
843 | """Class to handle link protection.""" |
||
844 | |||
845 | def is_affected_by_link(self, link=None): |
||
846 | """Verify if the current path is affected by link down event.""" |
||
847 | return self.current_path.is_affected_by_link(link) |
||
848 | |||
849 | def is_using_primary_path(self): |
||
850 | """Verify if the current deployed path is self.primary_path.""" |
||
851 | return self.current_path == self.primary_path |
||
852 | |||
853 | def is_using_backup_path(self): |
||
854 | """Verify if the current deployed path is self.backup_path.""" |
||
855 | return self.current_path == self.backup_path |
||
856 | |||
857 | def is_using_dynamic_path(self): |
||
858 | """Verify if the current deployed path is dynamic.""" |
||
859 | if self.current_path and \ |
||
860 | not self.is_using_primary_path() and \ |
||
861 | not self.is_using_backup_path() and \ |
||
862 | self.current_path.status is EntityStatus.UP: |
||
863 | return True |
||
864 | return False |
||
865 | |||
866 | def deploy_to(self, path_name=None, path=None): |
||
867 | """Create a deploy to path.""" |
||
868 | if self.current_path == path: |
||
869 | log.debug(f'{path_name} is equal to current_path.') |
||
870 | return True |
||
871 | |||
872 | if path.status is EntityStatus.UP: |
||
873 | return self.deploy_to_path(path) |
||
874 | |||
875 | return False |
||
876 | |||
877 | def handle_link_up(self, link): |
||
878 | """Handle circuit when link down. |
||
879 | |||
880 | Args: |
||
881 | link(Link): Link affected by link.down event. |
||
882 | |||
883 | """ |
||
884 | if self.is_using_primary_path(): |
||
885 | return True |
||
886 | |||
887 | success = False |
||
888 | if self.primary_path.is_affected_by_link(link): |
||
889 | success = self.deploy_to_primary_path() |
||
890 | |||
891 | if success: |
||
892 | return True |
||
893 | |||
894 | # We tried to deploy(primary_path) without success. |
||
895 | # And in this case is up by some how. Nothing to do. |
||
896 | if self.is_using_backup_path() or self.is_using_dynamic_path(): |
||
897 | return True |
||
898 | |||
899 | # In this case, probably the circuit is not being used and |
||
900 | # we can move to backup |
||
901 | if self.backup_path.is_affected_by_link(link): |
||
902 | success = self.deploy_to_backup_path() |
||
903 | |||
904 | if success: |
||
905 | return True |
||
906 | |||
907 | # In this case, the circuit is not being used and we should |
||
908 | # try a dynamic path |
||
909 | if self.dynamic_backup_path: |
||
910 | return self.deploy_to_path() |
||
911 | |||
912 | return True |
||
913 | |||
914 | def handle_link_down(self): |
||
915 | """Handle circuit when link down. |
||
916 | |||
917 | Returns: |
||
918 | bool: True if the re-deploy was successly otherwise False. |
||
919 | |||
920 | """ |
||
921 | success = False |
||
922 | if self.is_using_primary_path(): |
||
923 | success = self.deploy_to_backup_path() |
||
924 | elif self.is_using_backup_path(): |
||
925 | success = self.deploy_to_primary_path() |
||
926 | |||
927 | if not success and self.dynamic_backup_path: |
||
928 | success = self.deploy_to_path() |
||
929 | |||
930 | if success: |
||
931 | log.debug(f"{self} deployed after link down.") |
||
932 | else: |
||
933 | self.deactivate() |
||
934 | self.current_path = Path([]) |
||
935 | self.sync() |
||
936 | log.debug(f'Failed to re-deploy {self} after link down.') |
||
937 | |||
938 | return success |
||
939 | |||
940 | |||
941 | class EVC(LinkProtection): |
||
942 | """Class that represents a E-Line Virtual Connection.""" |
||
943 |