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