blob: 5e00bcae3b4bc545db5a2efaa064eef181a7c85a [file] [log] [blame]
Chip Bolingf5af85d2019-02-12 15:36:17 -06001# Copyright 2017-present Adtran, Inc.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import xmltodict
16import re
17import structlog
18from enum import IntEnum
19from twisted.internet import reactor, defer
20from twisted.internet.defer import inlineCallbacks, returnValue, succeed
21
22log = structlog.get_logger()
23
24EVC_NAME_FORMAT = 'VOLTHA-{}' # format(flow.id)
25EVC_NAME_REGEX_ALL = EVC_NAME_FORMAT.format('*')
26DEFAULT_STPID = 0x8100
27
28
29class EVC(object):
30 """
31 Class to wrap EVC functionality
32 """
33 class SwitchingMethod(IntEnum):
34 SINGLE_TAGGED = 1
35 DOUBLE_TAGGED = 2
36 MAC_SWITCHED = 3
37 DOUBLE_TAGGED_MAC_SWITCHED = 4
38 DEFAULT = SINGLE_TAGGED
39
40 @staticmethod
41 def xml(value):
42 if value is None:
43 value = EVC.SwitchingMethod.DEFAULT
44 if value == EVC.SwitchingMethod.SINGLE_TAGGED:
45 return '<single-tag-switched/>'
46 elif value == EVC.SwitchingMethod.DOUBLE_TAGGED:
47 return '<double-tag-switched/>'
48 elif value == EVC.SwitchingMethod.MAC_SWITCHED:
49 return '<mac-switched/>'
50 elif value == EVC.SwitchingMethod.DOUBLE_TAGGED_MAC_SWITCHED:
51 return '<double-tag-mac-switched/>'
52 raise ValueError('Invalid SwitchingMethod enumeration')
53
54 class Men2UniManipulation(IntEnum):
55 SYMMETRIC = 1
56 POP_OUT_TAG_ONLY = 2
57 DEFAULT = SYMMETRIC
58
59 @staticmethod
60 def xml(value):
61 if value is None:
62 value = EVC.Men2UniManipulation.DEFAULT
63 fmt = '<men-to-uni-tag-manipulation>{}</men-to-uni-tag-manipulation>'
64 if value == EVC.Men2UniManipulation.SYMMETRIC:
65 return fmt.format('<symmetric/>')
66 elif value == EVC.Men2UniManipulation.POP_OUT_TAG_ONLY:
67 return fmt.format('<pop-outer-tag-only/>')
68 raise ValueError('Invalid Men2UniManipulation enumeration')
69
70 class ElineFlowType(IntEnum):
71 NNI_TO_UNI = 1
72 UNI_TO_NNI = 2
73 NNI_TO_NNI = 3
74 UNI_TO_UNI = 4
75 ACL_FILTER = 5
76 UNKNOWN = 6
77 UNSUPPORTED = 7 # Or Invalid
78
79 def __init__(self, flow_entry):
80 self._installed = False
81 self._status_message = None
82 self._flow = flow_entry
83 self._name = self._create_name()
84 self._deferred = None
85 self._evc_maps = {} # Map Name -> evc-map
86
87 self._flow_type = EVC.ElineFlowType.UNKNOWN
88
89 # EVC related properties
90 self._enabled = True
91 self._men_ports = []
92 self._s_tag = None
93 self._stpid = None
94 self._switching_method = None
95 self.service_evc = False
96
97 self._ce_vlan_preservation = None
98 self._men_to_uni_tag_manipulation = None
99
100 try:
101 self._valid = self._decode()
102
103 except Exception as e:
104 log.exception('Failure during EVC decode', e=e)
105 self._valid = False
106
107 def __str__(self):
108 return "EVC-{}: MEN: {}, S-Tag: {}".format(self._name, self._men_ports, self._s_tag)
109
110 def _create_name(self):
111 #
112 # TODO: Take into account selection criteria and output to make the name
113 #
114 return EVC_NAME_FORMAT.format(self._flow.flow_id)
115
116 def _cancel_deferred(self):
117 d, self._deferred = self._deferred, None
118
119 try:
120 if d is not None and not d.called:
121 d.cancel()
122
123 except Exception as e:
124 pass
125
126 @property
127 def name(self):
128 return self._name
129
130 @property
131 def valid(self):
132 return self._valid
133
134 @property
135 def installed(self):
136 return self._installed
137
138 @installed.setter
139 def installed(self, value):
140 assert not value, 'EVC Install can only be reset'
141 self._installed = False
142
143 @property
144 def status(self):
145 return self._status_message
146
147 @status.setter
148 def status(self, value):
149 self._status_message = value
150
151 @property
152 def s_tag(self):
153 return self._s_tag
154
155 @property
156 def stpid(self):
157 return self._stpid
158
159 @stpid.setter
160 def stpid(self, value):
161 assert self._stpid is None or self._stpid == value, 'STPID can only be set once'
162 self._stpid = value
163
164 @property
165 def switching_method(self):
166 return self._switching_method
167
168 @switching_method.setter
169 def switching_method(self, value):
170 assert self._switching_method is None or self._switching_method == value,\
171 'Switching Method can only be set once. EVC: {}'.format(self.name)
172 self._switching_method = value
173
174 @property
175 def ce_vlan_preservation(self):
176 return self._ce_vlan_preservation
177
178 @ce_vlan_preservation.setter
179 def ce_vlan_preservation(self, value):
180 assert self._ce_vlan_preservation is None or self._ce_vlan_preservation == value,\
181 'CE VLAN Preservation can only be set once'
182 self._ce_vlan_preservation = value
183
184 @property
185 def men_to_uni_tag_manipulation(self):
186 return self._men_to_uni_tag_manipulation
187
188 @men_to_uni_tag_manipulation.setter
189 def men_to_uni_tag_manipulation(self, value):
190 assert self._men_to_uni_tag_manipulation is None or self._men_to_uni_tag_manipulation == value, \
191 'MEN-to-UNI tag manipulation can only be set once'
192 self._men_to_uni_tag_manipulation = value
193
194 @property
195 def flow_entry(self):
196 # Note that the first flow used to create the EVC is saved and it may
197 # eventually get deleted while others still use the EVC. This should
198 # be okay as the downstream flow/signature table is used to maintain
199 # the lifetime on this EVC object.
200 return self._flow
201
202 @flow_entry.setter
203 def flow_entry(self, value):
204 self._flow = value
205
206 @property
207 def evc_maps(self):
208 """
209 Get all EVC Maps that reference this EVC
210 :return: list of EVCMap
211 """
212 return list(self._evc_maps.values()) if self._evc_maps is not None else []
213
214 @property
215 def evc_map_names(self):
216 """
217 Get all EVC Map names that reference this EVC
218 :return: list of EVCMap names
219 """
220 return list(self._evc_maps.keys()) if self._evc_maps is not None else []
221
222 def add_evc_map(self, evc_map):
223 if self._evc_maps is None:
224 self._evc_maps = dict()
225
226 if evc_map.name not in self._evc_maps:
227 self._evc_maps[evc_map.name] = evc_map
228
229 def remove_evc_map(self, evc_map):
230 if self._evc_maps is not None and evc_map.name in self._evc_maps:
231 del self._evc_maps[evc_map.name]
232
233 def schedule_install(self, delay=0):
234 """
235 Try to install EVC and all MAPs in a single operational sequence.
236 The delay parameter is used during recovery to allow multiple associated
237 EVC maps to be updated/modified independently before the parent EVC
238 is installed.
239
240 :param delay: (int) Seconds to delay before install
241 """
242 self._cancel_deferred()
243
244 self._deferred = reactor.callLater(delay, self._do_install) \
245 if self._valid else succeed('Not VALID')
246
247 return self._deferred
248
249 @staticmethod
250 def _xml_header(operation=None):
251 return '<evcs xmlns="http://www.adtran.com/ns/yang/adtran-evcs"{}><evc>'.\
252 format('' if operation is None else ' xc:operation="{}"'.format(operation))
253
254 @staticmethod
255 def _xml_trailer():
256 return '</evc></evcs>'
257
258 @inlineCallbacks
259 def _do_install(self):
260 # Install the EVC if needed
261 log.debug('do-install', valid=self._valid, installed=self._installed)
262
263 if self._valid and not self._installed:
264 # TODO: Currently install EVC and then MAPs. Can do it all in a single edit-config operation
265
266 xml = EVC._xml_header()
267 xml += '<name>{}</name>'.format(self.name)
268 xml += '<enabled>{}</enabled>'.format('true' if self._enabled else 'false')
269
270 if self._ce_vlan_preservation is not None:
271 xml += '<ce-vlan-preservation>{}</ce-vlan-preservation>'.format('false')
272
273 if self._s_tag is not None:
274 xml += '<stag>{}</stag>'.format(self._s_tag)
275 xml += '<stag-tpid>{}</stag-tpid>'.format(self._stpid or DEFAULT_STPID)
276 else:
277 xml += 'no-stag/'
278
279 for port in self._men_ports:
280 xml += '<men-ports>{}</men-ports>'.format(port)
281
282 # xml += EVC.Men2UniManipulation.xml(self._men_to_uni_tag_manipulation)
283 # xml += EVC.SwitchingMethod.xml(self._switching_method)
284 xml += EVC._xml_trailer()
285
286 log.debug('create-evc', name=self.name, xml=xml)
287 try:
288 # Set installed to true while request is in progress
289 self._installed = True
290 results = yield self._flow.handler.netconf_client.edit_config(xml)
291 self._installed = results.ok
292 self.status = '' if results.ok else results.error
293
294 except Exception as e:
295 log.exception('install-failed', name=self.name, e=e)
296 raise
297
298 # Install any associated EVC Maps
299
300 if self._installed:
301 for evc_map in self.evc_maps:
302 try:
303 yield evc_map.install()
304
305 except Exception as e:
306 evc_map.status = 'Exception during EVC-MAP Install: {}'.format(e.message)
307 log.exception('evc-map-install-failed', e=e)
308
309 returnValue(self._installed and self._valid)
310
311 def remove(self, remove_maps=True):
312 """
313 Remove EVC (and optional associated EVC-MAPs) from hardware
314 :param remove_maps: (boolean)
315 :return: (deferred)
316 """
317 if not self.installed:
318 return succeed('Not installed')
319
320 log.info('removing', evc=self, remove_maps=remove_maps)
321 dl = []
322
323 def _success(rpc_reply):
324 log.debug('remove-success', rpc_reply=rpc_reply)
325 self._installed = False
326
327 def _failure(results):
328 log.error('remove-failed', results=results)
329 self._installed = False
330
331 xml = EVC._xml_header('delete') + '<name>{}</name>'.format(self.name) + EVC._xml_trailer()
332 d = self._flow.handler.netconf_client.edit_config(xml)
333 d.addCallbacks(_success, _failure)
334 dl.append(d)
335
336 if remove_maps:
337 for evc_map in self.evc_maps:
338 dl.append(evc_map.remove())
339
340 return defer.gatherResults(dl, consumeErrors=True)
341
342 @inlineCallbacks
343 def delete(self, delete_maps=True):
344 """
345 Remove from hardware and delete/clean-up EVC Object
346 """
347 log.info('deleting', evc=self, delete_maps=delete_maps)
348
349 assert self._flow, 'Delete EVC must have flow reference'
350 try:
351 dl = [self.remove()]
352 self._valid = False
353
354 if delete_maps:
355 for evc_map in self.evc_maps:
356 dl.append(evc_map.delete(None)) # TODO: implement bulk-flow procedures
357
358 yield defer.gatherResults(dl, consumeErrors=True)
359
360 except Exception as e:
361 log.exception('removal', e=e)
362
363 self._evc_maps = None
364 f, self._flow = self._flow, None
365 if f is not None and f.handler is not None:
366 f.handler.remove_evc(self)
367
368 returnValue('Done')
369
370 def reflow(self, reflow_maps=True):
371 """
372 Attempt to install/re-install a flow
373 :param reflow_maps: (boolean) Flag indication if EVC-MAPs should be reflowed as well
374 :return: (deferred)
375 """
376 self._installed = False
377
378 if reflow_maps:
379 for evc_map in self.evc_maps:
380 evc_map.installed = False
381
382 return self.schedule_install()
383
384 def _decode(self):
385 """
386 Examine flow rules and extract appropriate settings for this EVC
387 """
388 if self._flow.handler.is_nni_port(self._flow.in_port):
389 self._men_ports.append(self._flow.handler.get_port_name(self._flow.in_port))
390 else:
391 self._status_message = 'EVCs with UNI ports are not supported'
392 return False # UNI Ports handled in the EVC Maps
393
394 self._s_tag = self._flow.vlan_id
395
396 if self._flow.inner_vid is not None:
397 self._switching_method = EVC.SwitchingMethod.DOUBLE_TAGGED
398
399 # For the Utility VLAN, multiple ingress ACLs (different GEMs) will need to
400 # be trapped on this EVC. Since these are usually untagged, we have to force
401 # the EVC to preserve CE VLAN tags.
402
403 if self._s_tag == self._flow.handler.utility_vlan:
404 self._ce_vlan_preservation = True
405
406 # Note: The following fields may get set when the first EVC-MAP
407 # is associated with this object. Once set, they cannot be changed to
408 # another value.
409 # self._stpid
410 # self._switching_method
411 # self._ce_vlan_preservation
412 # self._men_to_uni_tag_manipulation
413 return True
414
415 # BULK operations
416
417 @staticmethod
418 def remove_all(client, regex_=EVC_NAME_REGEX_ALL):
419 """
420 Remove all matching EVCs from hardware
421 :param client: (ncclient) NETCONF Client to use
422 :param regex_: (String) Regular expression for name matching
423 :return: (deferred)
424 """
425 # Do a 'get' on the evc config an you should get the names
426 get_xml = """
427 <filter xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
428 <evcs xmlns="http://www.adtran.com/ns/yang/adtran-evcs">
429 <evc><name/></evc>
430 </evcs>
431 </filter>
432 """
433 log.debug('query', xml=get_xml, regex=regex_)
434
435 def request_failed(results, operation):
436 log.error('{}-failed'.format(operation), results=results)
437 # No further actions. Periodic poll later on will scrub any old EVCs if needed
438
439 def delete_complete(results):
440 log.debug('delete-complete', results=results)
441
442 def do_delete(rpc_reply, regexpr):
443 log.debug('query-complete', rpc_reply=rpc_reply)
444
445 if rpc_reply.ok:
446 result_dict = xmltodict.parse(rpc_reply.data_xml)
447 entries = result_dict['data']['evcs'] if 'evcs' in result_dict['data'] else {}
448
449 if 'evc' in entries:
450 p = re.compile(regexpr)
451
452 if isinstance(entries['evc'], list):
453 names = {entry['name'] for entry in entries['evc'] if 'name' in entry
454 and p.match(entry['name'])}
455 else:
456 names = set()
457 for item in entries['evc'].items():
458 if isinstance(item, tuple) and item[0] == 'name':
459 names.add(item[1])
460 break
461
462 if len(names) > 0:
463 del_xml = '<evcs xmlns="http://www.adtran.com/ns/yang/adtran-evcs"' + \
464 ' xc:operation = "delete">'
465 for name in names:
466 del_xml += '<evc>'
467 del_xml += '<name>{}</name>'.format(name)
468 del_xml += '</evc>'
469 del_xml += '</evcs>'
470 log.debug('removing', xml=del_xml)
471
472 return client.edit_config(del_xml)
473
474 return succeed('no entries')
475
476 d = client.get(get_xml)
477 d.addCallbacks(do_delete, request_failed, callbackArgs=[regex_], errbackArgs=['get'])
478 d.addCallbacks(delete_complete, request_failed, errbackArgs=['edit-config'])
479 return d