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