565ed486d83ccd60a0c9004b95b3f50245bb2b63
[csit.git] / resources / libraries / python / honeycomb / HcAPIKwACL.py
1 # Copyright (c) 2016 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 ACL data structures using
15 Honeycomb REST API."""
16 from robot.api import logger
17
18 from resources.libraries.python.topology import Topology
19 from resources.libraries.python.HTTPRequest import HTTPCodes
20 from resources.libraries.python.honeycomb.HoneycombSetup import HoneycombError
21 from resources.libraries.python.honeycomb.HoneycombUtil \
22     import HoneycombUtil as HcUtil
23 from resources.libraries.python.honeycomb.HoneycombUtil \
24     import DataRepresentation
25
26
27 class ACLKeywords(object):
28     """Implementation of keywords which make it possible to:
29     - add classify table(s),
30     - remove classify table(s),
31     - get operational data about classify table(s),
32     - add classify session(s),
33     - remove classify session(s),
34     - get operational data about classify sessions(s).
35     """
36
37     def __init__(self):
38         pass
39
40     @staticmethod
41     def _set_classify_table_properties(node, path, data=None):
42         """Set classify table 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         :return: Content of response.
51         :rtype: bytearray
52         :raises HoneycombError: If the status code in response to PUT is not
53         200 = OK.
54         """
55
56         if data:
57             status_code, resp = HcUtil.\
58                 put_honeycomb_data(node, "config_classify_table", data, path,
59                                    data_representation=DataRepresentation.JSON)
60         else:
61             status_code, resp = HcUtil.\
62                 delete_honeycomb_data(node, "config_classify_table", path)
63
64         if status_code not in (HTTPCodes.OK, HTTPCodes.ACCEPTED):
65             if data is None and '"error-tag":"data-missing"' in resp:
66                 logger.debug("data does not exist in path.")
67             else:
68                 raise HoneycombError(
69                     "The configuration of classify table was not successful. "
70                     "Status code: {0}.".format(status_code))
71         return resp
72
73     @staticmethod
74     def add_classify_table(node, table):
75         """Add a classify table to the list of classify tables. The keyword does
76         not validate given data.
77
78         :param node: Honeycomb node.
79         :param table: Classify table to be added.
80         :type node: dict
81         :type table: dict
82         :return: Content of response.
83         :rtype: bytearray
84         """
85
86         path = "/classify-table/" + table["name"]
87         data = {"classify-table": [table, ]}
88         return ACLKeywords._set_classify_table_properties(node, path, data)
89
90     @staticmethod
91     def remove_all_classify_tables(node):
92         """Remove all classify tables defined on the node.
93
94         :param node: Honeycomb node.
95         :type node: dict
96         :return: Content of response.
97         :rtype: bytearray
98         """
99
100         return ACLKeywords._set_classify_table_properties(node, path="")
101
102     @staticmethod
103     def remove_classify_table(node, table_name):
104         """Remove the given classify table.
105
106         :param node: Honeycomb node.
107         :param table_name: Name of the classify table to be removed.
108         :type node: dict
109         :type table_name: str
110         :return: Content of response.
111         :rtype: bytearray
112         """
113
114         path = "/classify-table/" + table_name
115         return ACLKeywords._set_classify_table_properties(node, path)
116
117     @staticmethod
118     def get_all_classify_tables_oper_data(node):
119         """Get operational data about all classify tables present on the node.
120
121         :param node: Honeycomb node.
122         :type node: dict
123         :return: List of classify tables.
124         :rtype: list
125         """
126
127         status_code, resp = HcUtil.\
128             get_honeycomb_data(node, "oper_classify_table")
129
130         if status_code != HTTPCodes.OK:
131             raise HoneycombError(
132                 "Not possible to get operational information about the "
133                 "classify tables. Status code: {0}.".format(status_code))
134         try:
135             return resp["vpp-classifier"]["classify-table"]
136         except (KeyError, TypeError):
137             return []
138
139     @staticmethod
140     def get_classify_table_oper_data(node, table_name):
141         """Get operational data about the given classify table.
142
143         :param node: Honeycomb node.
144         :param table_name: Name of the classify table.
145         :type node: dict
146         :type table_name: str
147         :return: Operational data about the given classify table.
148         :rtype: dict
149         """
150
151         path = "/classify-table/" + table_name
152         status_code, resp = HcUtil.\
153             get_honeycomb_data(node, "oper_classify_table", path)
154
155         if status_code != HTTPCodes.OK:
156             raise HoneycombError(
157                 "Not possible to get operational information about the "
158                 "classify tables. Status code: {0}.".format(status_code))
159         try:
160             return resp["classify-table"][0]
161         except (KeyError, TypeError):
162             return []
163
164     @staticmethod
165     def get_all_classify_tables_cfg_data(node):
166         """Get configuration data about all classify tables present on the node.
167
168         :param node: Honeycomb node.
169         :type node: dict
170         :return: List of classify tables.
171         :rtype: list
172         """
173
174         status_code, resp = HcUtil.\
175             get_honeycomb_data(node, "config_classify_table")
176
177         if status_code != HTTPCodes.OK:
178             raise HoneycombError(
179                 "Not possible to get operational information about the "
180                 "classify tables. Status code: {0}.".format(status_code))
181         try:
182             return resp["vpp-classifier"]["classify-table"]
183         except (KeyError, TypeError):
184             return []
185
186     @staticmethod
187     def add_classify_session(node, table_name, session):
188         """Add a classify session to the classify table.
189
190         :param node: Honeycomb node.
191         :param table_name: Name of the classify table.
192         :param session: Classify session to be added to the classify table.
193         :type node: dict
194         :type table_name: str
195         :type session: dict
196         :return: Content of response.
197         :rtype: bytearray
198         """
199
200         path = "/classify-table/" + table_name + \
201                "/classify-session/" + session["match"]
202         data = {"classify-session": [session, ]}
203         return ACLKeywords._set_classify_table_properties(node, path, data)
204
205     @staticmethod
206     def remove_classify_session(node, table_name, session_match):
207         """Remove the given classify session from the classify table.
208
209         :param node: Honeycomb node.
210         :param table_name: Name of the classify table.
211         :param session_match: Classify session match.
212         :type node: dict
213         :type table_name: str
214         :type session_match: str
215         :return: Content of response.
216         :rtype: bytearray
217         """
218
219         path = "/classify-table/" + table_name + \
220                "/classify-session/" + session_match
221         return ACLKeywords._set_classify_table_properties(node, path)
222
223     @staticmethod
224     def get_all_classify_sessions_oper_data(node, table_name):
225         """Get operational data about all classify sessions in the classify
226         table.
227
228         :param node: Honeycomb node.
229         :param table_name: Name of the classify table.
230         :type node: dict
231         :type table_name: str
232         :return: List of classify sessions present in the classify table.
233         :rtype: list
234         """
235
236         table_data = ACLKeywords.get_classify_table_oper_data(node, table_name)
237         try:
238             return table_data["classify-table"][0]["classify-session"]
239         except (KeyError, TypeError):
240             return []
241
242     @staticmethod
243     def get_classify_session_oper_data(node, table_name, session_match):
244         """Get operational data about the given classify session in the classify
245         table.
246
247         :param node: Honeycomb node.
248         :param table_name: Name of the classify table.
249         :param session_match: Classify session match.
250         :type node: dict
251         :type table_name: str
252         :type session_match: str
253         :return: Classify session operational data.
254         :rtype: dict
255         """
256
257         path = "/classify-table/" + table_name + \
258                "/classify-session/" + session_match
259         status_code, resp = HcUtil.\
260             get_honeycomb_data(node, "oper_classify_table", path)
261
262         if status_code != HTTPCodes.OK:
263             raise HoneycombError(
264                 "Not possible to get operational information about the "
265                 "classify tables. Status code: {0}.".format(status_code))
266         try:
267             return resp["classify-session"][0]
268         except (KeyError, TypeError):
269             return {}
270
271     @staticmethod
272     def create_acl_plugin_classify_chain(node, list_name, data, macip=False):
273         """Create classify chain using the ietf-acl node.
274
275         :param node: Honeycomb node.
276         :param list_name: Name for the classify list.
277         :param data: Dictionary of settings to send to Honeycomb.
278         :param macip: Use simple MAC+IP classifier. Optional.
279         :type node: dict
280         :type list_name: str
281         :type data: dict
282         :type macip: bool
283
284         :return: Content of response.
285         :rtype: bytearray
286         :raises HoneycombError: If the operation fails.
287         """
288
289         if macip:
290             path = "/acl/vpp-acl:vpp-macip-acl/{0}".format(list_name)
291         else:
292             path = "/acl/vpp-acl:vpp-acl/{0}".format(list_name)
293
294         status_code, resp = HcUtil.put_honeycomb_data(
295             node, "config_plugin_acl", data, path)
296
297         if status_code not in (HTTPCodes.OK, HTTPCodes.ACCEPTED):
298             raise HoneycombError(
299                 "Could not create classify chain."
300                 "Status code: {0}.".format(status_code))
301
302         return resp
303
304     @staticmethod
305     def set_acl_plugin_interface(node, interface, acl_name,
306                                  direction, macip=False):
307         """Assign an interface to an ietf-acl classify chain.
308
309         :param node: Honeycomb node.
310         :param interface: Name of an interface on the node.
311         :param acl_name: Name of an ACL chain configured through ACL-plugin.
312         :param direction: Classify incoming or outgiong packets.
313         Valid options are: ingress, egress
314         :param macip: Use simple MAC+IP classifier. Optional.
315         :type node: dict
316         :type interface: str or int
317         :type acl_name: str
318         :type direction: str
319         :type macip: bool
320
321         :return: Content of response.
322         :rtype: bytearray
323         :raises HoneycombError: If the operation fails.
324         """
325
326         interface = Topology.convert_interface_reference(
327             node, interface, "name")
328
329         interface = interface.replace("/", "%2F")
330
331         if direction not in ("ingress", "egress"):
332             raise ValueError("Unknown traffic direction {0}. "
333                              "Valid options are: ingress, egress."
334                              .format(direction))
335
336         path = "/interface/{0}/interface-acl:acl/{1}".format(
337             interface, direction)
338
339         if macip:
340             data = {
341                 direction: {
342                     "vpp-macip-acl": {
343                         "type": "vpp-acl:vpp-macip-acl",
344                         "name": acl_name
345                     }
346                 }
347             }
348         else:
349             data = {
350                 direction: {
351                     "vpp-acls": [
352                         {
353                             "type": "vpp-acl:vpp-acl",
354                             "name": acl_name
355                         }
356                     ]
357                 }
358             }
359
360         status_code, resp = HcUtil.put_honeycomb_data(
361             node, "config_vpp_interfaces", data, path)
362
363         if status_code not in (HTTPCodes.OK, HTTPCodes.ACCEPTED):
364             raise HoneycombError(
365                 "Could not configure ACL on interface. "
366                 "Status code: {0}.".format(status_code))
367
368         return resp
369
370     @staticmethod
371     def delete_interface_plugin_acls(node, interface):
372         """Remove all plugin-acl assignments from an interface.
373
374         :param node: Honeycomb node.
375         :param interface: Name of an interface on the node.
376         :type node: dict
377         :type interface: str or int
378         """
379
380         interface = Topology.convert_interface_reference(
381             node, interface, "name")
382
383         interface = interface.replace("/", "%2F")
384
385         path = "/interface/{0}/interface-acl:acl/".format(interface)
386         status_code, _ = HcUtil.delete_honeycomb_data(
387             node, "config_vpp_interfaces", path)
388
389         if status_code != HTTPCodes.OK:
390             raise HoneycombError(
391                 "Could not remove ACL assignment from interface. "
392                 "Status code: {0}.".format(status_code))
393
394     @staticmethod
395     def delete_acl_plugin_classify_chains(node):
396         """Remove all plugin-ACL classify chains.
397
398         :param node: Honeycomb node.
399         :type node: dict
400         """
401
402         status_code, _ = HcUtil.delete_honeycomb_data(
403             node, "config_plugin_acl")
404
405         if status_code != HTTPCodes.OK:
406             raise HoneycombError(
407                 "Could not remove plugin-acl chain. "
408                 "Status code: {0}.".format(status_code))