Fix Tap failing tests
[csit.git] / resources / libraries / python / honeycomb / Lisp.py
1 # Copyright (c) 2018 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 """This module implements keywords to manipulate LISP data structures using
15 Honeycomb REST API."""
16
17 from resources.libraries.python.HTTPRequest import HTTPCodes
18 from resources.libraries.python.honeycomb.HoneycombSetup import HoneycombError
19 from resources.libraries.python.honeycomb.HoneycombUtil \
20     import HoneycombUtil as HcUtil
21 from resources.libraries.python.honeycomb.HoneycombUtil \
22     import DataRepresentation
23 from resources.libraries.python.topology import Topology
24
25
26 class LispKeywords(object):
27     """Implementation of keywords which make it possible to:
28     - enable/disable LISP feature
29     - configure LISP mappings
30     - configure locator sets
31     - configure map resolver
32     - configure LISP PITR feature
33     - read operational data for all of the above
34     """
35
36     def __init__(self):
37         """Initializer."""
38         pass
39
40     @staticmethod
41     def _set_lisp_properties(node, path, data=None):
42         """Set LISP properties and check the return code.
43
44         :param node: Honeycomb node.
45         :param path: Path which is added to the base path to identify the data.
46         :param data: The new data to be set. If None, the item will be removed.
47         :type node: dict
48         :type path: str
49         :type data: dict
50         :returns: Content of response.
51         :rtype: bytearray
52         :raises HoneycombError: If the status code in response to PUT is not
53             200 = OK or 201 = ACCEPTED.
54         """
55
56         if data:
57             status_code, resp = HcUtil.\
58                 put_honeycomb_data(node, "config_lisp", data, path,
59                                    data_representation=DataRepresentation.JSON)
60         else:
61             status_code, resp = HcUtil.\
62                 delete_honeycomb_data(node, "config_lisp", path)
63
64         if status_code not in (HTTPCodes.OK, HTTPCodes.ACCEPTED):
65             raise HoneycombError(
66                 "Lisp configuration unsuccessful. "
67                 "Status code: {0}.".format(status_code))
68         else:
69             return resp
70
71     @staticmethod
72     def get_lisp_operational_data(node):
73         """Retrieve Lisp properties from Honeycomb operational data.
74
75         :param node: Honeycomb node.
76         :type node: dict
77         :returns: List operational data.
78         :rtype: bytearray
79         """
80
81         status_code, resp = HcUtil.get_honeycomb_data(node, "oper_lisp")
82
83         if status_code != HTTPCodes.OK:
84             raise HoneycombError("Could not retrieve LISP operational data."
85                                  "Status code: {0}.".format(status_code))
86         else:
87             # get rid of empty vni-table entry
88             resp["lisp-state"]["lisp-feature-data"]["eid-table"][
89                 "vni-table"].remove(
90                     {
91                         "virtual-network-identifier": 0,
92                         "vrf-subtable": {"table-id": 0}
93                     }
94                 )
95             return resp
96
97     @staticmethod
98     def verify_map_server_data_from_honeycomb(data, ip_addresses):
99         """Verify whether MAP server data from Honeycomb is correct.
100
101         :param data: LISP operational data containing map server IP addresses.
102         :param ip_addresses: IP addresses to verify map server data against.
103         :type data: dict
104         :type ip_addresses: list
105         :returns: Boolean Value indicating equality of IP Lists.
106         :rtype: bool
107         """
108
109         data =\
110             data['lisp-state']['lisp-feature-data']['map-servers']['map-server']
111
112         data = sorted([entry['ip-address'] for entry in data])
113         ip_addresses.sort()
114
115         return data == ip_addresses
116
117     @staticmethod
118     def verify_map_server_data_from_vat(data, ip_addresses):
119         """Verify whether MAP server data from VAT is correct.
120
121         :param data: LISP operational data containing map server IP addresses.
122         :param ip_addresses: IP addresses to verify map server data against.
123         :type data: dict
124         :type ip_addresses: list
125         :returns: Boolean Value indicating equality of IP Lists.
126         :rtype: bool
127         """
128
129         data = sorted([entry['map-server'] for entry in data])
130         ip_addresses.sort()
131
132         return data == ip_addresses
133
134     @staticmethod
135     def set_lisp_state(node, state=True):
136         """Enable or disable the LISP feature.
137
138         :param node: Honeycomb node.
139         :param state: Enable or disable LISP.
140         :type node: dict
141         :type state: bool
142         :returns: Content of response.
143         :rtype: bytearray
144         :raises HoneycombError: If the return code is not 200:OK
145             or 404:NOT FOUND.
146         """
147
148         ret_code, data = HcUtil.get_honeycomb_data(node, "config_lisp")
149         if ret_code == HTTPCodes.OK:
150             data["lisp"]["enable"] = bool(state)
151         elif ret_code == HTTPCodes.NOT_FOUND:
152             data = {"lisp": {"enable": bool(state)}}
153         else:
154             raise HoneycombError("Unexpected return code when getting existing"
155                                  " LISP configuration.")
156
157         return LispKeywords._set_lisp_properties(node, '', data)
158
159     @staticmethod
160     def set_rloc_probe_state(node, state=False):
161         """Enable or disable the Routing Locator probe.
162
163         :param node: Honeycomb node.
164         :param state: Enable or Disable the Rloc probe.
165         :type node: dict
166         :type state: bool
167         :returns: Content of response.
168         :rtype: bytearray
169         """
170
171         path = "/lisp-feature-data/rloc-probe"
172
173         data = {
174             "rloc-probe": {
175                 "enabled": bool(state)
176             }
177         }
178
179         return LispKeywords._set_lisp_properties(node, path, data)
180
181     @staticmethod
182     def add_locator(node, interface, locator_set, priority=1, weight=1):
183         """Configure a new LISP locator set.
184
185         :param node: Honeycomb node.
186         :param interface: An interface on the node.
187         :param locator_set: Name for the new locator set.
188         :param priority: Priority parameter for the locator.
189         :param weight: Weight parameter for the locator.
190         :type node: dict
191         :type interface: str
192         :type locator_set: str
193         :type priority: int
194         :type weight: int
195         :returns: Content of response.
196         :rtype: bytearray
197         """
198
199         interface = Topology.convert_interface_reference(
200             node, interface, "name")
201
202         path = "/lisp-feature-data/locator-sets/locator-set" \
203                "/{0}".format(locator_set)
204
205         data = {
206             "locator-set": {
207                 "name": locator_set,
208                 "interface": {
209                     "interface-ref": interface,
210                     "priority": priority,
211                     "weight": weight
212                 }
213             }
214         }
215
216         return LispKeywords._set_lisp_properties(node, path, data)
217
218     @staticmethod
219     def configure_lisp_mapping(node, data):
220         """Modify eid-table configuration to the data provided.
221
222         :param node: Honeycomb node.
223         :param data: Settings for the LISP mappings.
224         :type node: dict
225         :type data: dict
226         :returns: Content of response.
227         :rtype: bytearray
228         """
229
230         path = "/lisp-feature-data/eid-table"
231         return LispKeywords._set_lisp_properties(node, path, data)
232
233     @staticmethod
234     def configure_lisp_map_request_mode(node, option):
235         """Modify LISP Map Request Mode configuration to the data provided.
236
237         :param node: Honeycomb node.
238         :param option: Settings for the LISP map request mode.
239         :type node: dict
240         :type option: str
241         :returns: Content of response.
242         :rtype: bytearray
243         """
244
245         data = {
246             "map-request-mode": {
247                 "mode": option
248             }
249         }
250
251         path = "/lisp-feature-data/map-request-mode"
252         return LispKeywords._set_lisp_properties(node, path, data)
253
254     @staticmethod
255     def add_lisp_adjacency(node, vni_id, map_name, adjacency_name, data):
256         """Add an adjacency to an existing LISP mapping.
257
258         :param node: Honeycomb node.
259         :param vni_id: vni_id of the mapping.
260         :param map_name: Name of the mapping.
261         :param adjacency_name: Name for the new adjacency.
262         :param data: Adjacency settings.
263         :type node: dict
264         :type vni_id: int
265         :type map_name: str
266         :type adjacency_name: str
267         :type data: dict
268         :returns: Content of response.
269         :rtype: bytearray
270         """
271
272         path = (
273             "/lisp-feature-data/eid-table/vni-table/{vni_id}/"
274             "vrf-subtable/remote-mappings/remote-mapping/{map_name}/"
275             "adjacencies/adjacency/{adjacency_name}"
276         )
277         path = path.format(
278             vni_id=vni_id,
279             map_name=map_name,
280             adjacency_name=adjacency_name
281         )
282
283         return LispKeywords._set_lisp_properties(node, path, data)
284
285     @staticmethod
286     def add_map_resolver(node, ip_address):
287         """Configure map resolver with the specified IP address.
288
289         :param node: Honeycomb node.
290         :param ip_address: IP address to configure map resolver with.
291         :type node: dict
292         :type ip_address: str
293         :returns: Content of response.
294         :rtype: bytearray
295         """
296
297         path = "/lisp-feature-data/map-resolvers/map-resolver/{0}".format(
298             ip_address)
299
300         data = {
301             "map-resolver": {
302                 "ip-address": ip_address
303             }
304         }
305
306         return LispKeywords._set_lisp_properties(node, path, data)
307
308     @staticmethod
309     def set_map_register(node, map_register=False):
310         """Configure Map Register.
311
312         :param node: Honeycomb node.
313         :param map_register: Enable or disable Map Register.
314         :type node: dict
315         :type map_register: bool
316         :returns: Content of response.
317         :rtype: bytearray
318         """
319
320         path = "/lisp-feature-data/map-register"
321
322         data = {
323             "map-register": {
324                 "enabled": bool(map_register)
325             }
326         }
327
328         return LispKeywords._set_lisp_properties(node, path, data)
329
330     @staticmethod
331     def set_map_request_mode(node, src_dst=False):
332         """Configure Map Request Mode.
333
334         :param node: Honeycomb node.
335         :param src_dst: Configure Map Request Mode with source destination.
336         :type node: dict
337         :type src_dst: bool
338         :returns: Content of response.
339         :rtype: bytearray
340         """
341
342         path = "/lisp-feature-data/map-request-mode"
343
344         data = {
345             "map-request-mode": {
346                 "mode": "source-destination" if src_dst
347                         else "target-destination"
348             }
349         }
350
351         return LispKeywords._set_lisp_properties(node, path, data)
352
353     @staticmethod
354     def delete_map_resolver(node):
355         """Delete an existing map resolver.
356
357         :param node: Honeycomb node
358         :type node: dict
359         :returns: Content of response
360         :rtype: bytearray
361         """
362
363         path = "/lisp-feature-data/map-resolvers"
364
365         return LispKeywords._set_lisp_properties(node, path)
366
367     @staticmethod
368     def add_map_server(node, *ip_addresses):
369         """Configure map server with the specified IP addresses.
370
371         :param node: Honeycomb node.
372         :param ip_addresses: IP addresses to configure map server with.
373         :type node: dict
374         :type ip_addresses: list
375         :returns: Content of response.
376         :rtype: bytearray
377         """
378
379         path = "/lisp-feature-data/map-servers"
380
381         data = {
382             "map-servers": {
383                 "map-server": [
384                     {"ip-address": ip_address} for ip_address in ip_addresses
385                 ]
386             }
387         }
388
389         return LispKeywords._set_lisp_properties(node, path, data)
390
391     @staticmethod
392     def delete_map_server(node):
393         """Delete all map servers.
394
395         :param node: Honeycomb node
396         :type node: dict
397         :returns: Content of response
398         :rtype: bytearray
399         """
400
401         path = "/lisp-feature-data/map-servers"
402
403         return LispKeywords._set_lisp_properties(node, path)
404
405     @staticmethod
406     def configure_pitr(node, locator_set=None):
407         """Configure PITR feature with the specified locator set. If not locator
408         set is specified, disable PITR instead.
409
410         :param node: Honeycomb node.
411         :param locator_set: Name of a locator set. Optional.
412         :type node: dict
413         :type locator_set: str
414         :returns: Content of response.
415         :rtype: bytearray
416         """
417
418         path = "/lisp-feature-data/pitr-cfg"
419
420         if locator_set:
421             data = {
422                 "pitr-cfg": {
423                     "locator-set": locator_set
424                 }
425             }
426         else:
427             data = None
428
429         return LispKeywords._set_lisp_properties(node, path, data)
430
431     @staticmethod
432     def configure_petr(node, ip_address):
433         """Configure PETR feature with the specified IP. If no IP
434         specified, disable PETR instead.
435
436         :param node: Honeycomb node.
437         :param ip_address: IPv6 address.
438         :type node: dict
439         :type ip_address: str
440         :returns: Content of response.
441         :rtype: bytearray
442         """
443
444         path = "/lisp-feature-data/petr-cfg"
445
446         if ip_address:
447             data = {
448                 "petr-cfg": {
449                     "petr-address": ip_address
450                 }
451             }
452         else:
453             data = None
454
455         return LispKeywords._set_lisp_properties(node, path, data)
456
457     @staticmethod
458     def disable_lisp(node):
459         """Remove all LISP settings on the node.
460
461         :param node: Honeycomb node.
462         :type node: dict
463         :returns: Content of response.
464         :rtype: bytearray
465         """
466
467         return LispKeywords._set_lisp_properties(node, "")
468
469
470 class LispGPEKeywords(object):
471     """Implementation of keywords which make it possible to:
472     - enable/disable LISP GPE feature
473     - configure LISP GPE forwarding entries
474     - read operational data for all of the above
475     """
476
477     def __init__(self):
478         """Initializer."""
479         pass
480
481     @staticmethod
482     def _set_lispgpe_properties(node, path, data=None):
483         """Set LISP GPE properties and check the return code.
484
485         :param node: Honeycomb node.
486         :param path: Path which is added to the base path to identify the data.
487         :param data: The new data to be set. If None, the item will be removed.
488         :type node: dict
489         :type path: str
490         :type data: dict
491         :returns: Content of response.
492         :rtype: bytearray
493         :raises HoneycombError: If the status code in response to PUT is not
494             200 = OK or 201 = ACCEPTED.
495         """
496
497         if data:
498             status_code, resp = HcUtil.\
499                 put_honeycomb_data(node, "config_lisp_gpe", data, path,
500                                    data_representation=DataRepresentation.JSON)
501         else:
502             status_code, resp = HcUtil.\
503                 delete_honeycomb_data(node, "config_lisp_gpe", path)
504
505         if status_code not in (HTTPCodes.OK, HTTPCodes.ACCEPTED):
506             raise HoneycombError(
507                 "Lisp GPE configuration unsuccessful. "
508                 "Status code: {0}.".format(status_code))
509         else:
510             return resp
511
512     @staticmethod
513     def get_lispgpe_operational_data(node):
514         """Retrieve LISP GPE properties from Honeycomb operational data.
515
516         :param node: Honeycomb node.
517         :type node: dict
518         :returns: LISP GPE operational data.
519         :rtype: bytearray
520         :raises HoneycombError: If the status code in response to GET is not
521             200 = OK.
522         """
523
524         status_code, resp = HcUtil.get_honeycomb_data(node, "oper_lisp_gpe")
525
526         if status_code != HTTPCodes.OK:
527             raise HoneycombError("Could not retrieve Lisp GPE operational data."
528                                  "Status code: {0}.".format(status_code))
529         else:
530             return resp
531
532     @staticmethod
533     def get_lispgpe_mapping(node, name):
534         """Retrieve LISP GPE operational data and parse for a specific mapping.
535
536         :param node: Honeycomb node.
537         :param name: Name of the mapping to look for.
538         :type node: dict
539         :type name: str
540         :returns: LISP GPE mapping.
541         :rtype: dict
542         :raises HoneycombError: If the mapping is not present in operational
543             data.
544         """
545
546         data = LispGPEKeywords.get_lispgpe_operational_data(node)
547         try:
548             data = data["gpe-state"]["gpe-feature-data"]["gpe-entry-table"] \
549                 ["gpe-entry"]
550         except KeyError:
551             raise HoneycombError("No mappings present in operational data.")
552         for item in data:
553             if item["id"] == name:
554                 mapping = item
555                 break
556         else:
557             raise HoneycombError("Mapping with name {name} not found in "
558                                  "operational data.".format(name=name))
559
560         return mapping
561
562     @staticmethod
563     def get_lispgpe_config_data(node):
564         """Retrieve LISP GPE properties from Honeycomb config data.
565
566         :param node: Honeycomb node.
567         :type node: dict
568         :returns: LISP GPE config data.
569         :rtype: bytearray
570         :raises HoneycombError: If the status code in response to GET is not
571             200 = OK.
572         """
573
574         status_code, resp = HcUtil.get_honeycomb_data(node, "config_lisp_gpe")
575
576         if status_code != HTTPCodes.OK:
577             raise HoneycombError("Could not retrieve Lisp GPE config data."
578                                  "Status code: {0}.".format(status_code))
579         else:
580             return resp
581
582     @staticmethod
583     def set_lispgpe_state(node, state=True):
584         """Enable or disable the LISP GPE feature.
585
586         :param node: Honeycomb node.
587         :param state: Enable or disable LISP.
588         :type node: dict
589         :type state: bool
590         :returns: Content of response.
591         :rtype: bytearray
592         :raises HoneycombError: If the return code is not 200:OK
593             or 404:NOT FOUND.
594         """
595
596         ret_code, data = HcUtil.get_honeycomb_data(node, "config_lisp_gpe")
597         if ret_code == HTTPCodes.OK:
598             data["gpe"]["gpe-feature-data"]["enable"] = bool(state)
599         elif ret_code == HTTPCodes.NOT_FOUND:
600             data = {"gpe": {"gpe-feature-data": {"enable": bool(state)}}}
601         else:
602             raise HoneycombError("Unexpected return code when getting existing"
603                                  " Lisp GPE configuration.")
604
605         return LispGPEKeywords._set_lispgpe_properties(node, '', data)
606
607     @staticmethod
608     def configure_lispgpe_mapping(node, data=None):
609         """Modify LISP GPE mapping configuration to the data provided.
610
611         :param node: Honeycomb node.
612         :param data: Settings for the LISP GPE mappings.
613         :type node: dict
614         :type data: dict
615         :returns: Content of response.
616         :rtype: bytearray
617         """
618
619         path = "/gpe-feature-data/gpe-entry-table"
620         if data:
621             data = {"gpe-entry-table": {"gpe-entry": data}}
622             return LispGPEKeywords._set_lispgpe_properties(node, path, data)
623         else:
624             return LispGPEKeywords._set_lispgpe_properties(node, path)
625
626     @staticmethod
627     def add_lispgpe_mapping(node, name, data):
628         """Add the specified LISP GPE mapping.
629
630         :param node: Honeycomb node.
631         :param name: Name for the mapping.
632         :param data: Mapping details.
633         :type node: dict
634         :type name: str
635         :type data: dict
636         :returns: Content of response.
637         :rtype: bytearray
638         """
639
640         path = "/gpe-feature-data/gpe-entry-table/gpe-entry/{name}".format(
641             name=name)
642
643         data = {"gpe-entry": data}
644         return LispGPEKeywords._set_lispgpe_properties(node, path, data)
645
646     @staticmethod
647     def delete_lispgpe_mapping(node, mapping):
648         """Delete the specified LISP GPE mapping from configuration.
649
650         :param node: Honeycomb node.
651         :param mapping: Name of the mapping to remove.
652         :type node: dict
653         :type mapping: str
654         :returns: Content of response.
655         :rtype: bytearray
656         """
657
658         path = "/gpe-feature-data/gpe-entry-table/gpe-entry/{0}".format(mapping)
659         return LispGPEKeywords._set_lispgpe_properties(node, path)
660
661     @staticmethod
662     def disable_lispgpe(node):
663         """Remove all LISP GPE settings on the node.
664
665         :param node: Honeycomb node.
666         :type node: dict
667         :returns: Content of response.
668         :rtype: bytearray
669         """
670
671         return LispGPEKeywords._set_lispgpe_properties(node, "")