c4dc3a067aeca399384406f1968e72619ace5d8a
[csit.git] / resources / libraries / python / HoneycombUtil.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 """Implements keywords used with Honeycomb."""
15
16 import os.path
17 from json import loads
18
19 from robot.api import logger
20
21 from resources.libraries.python.topology import NodeType
22 from resources.libraries.python.HTTPRequest import HTTPRequest
23 from resources.libraries.python.constants import Constants as C
24
25
26 class HoneycombUtil(object):
27     """Implements keywords used with Honeycomb."""
28
29     def __init__(self):
30         pass
31
32     def get_configured_topology(self, nodes):
33         """Retrieves topology node IDs from each honeycomb node.
34
35         :param nodes: all nodes in topology
36         :type nodes: dict
37         :return: list of string IDs such as ['vpp1', 'vpp2']
38         :rtype list
39         """
40
41         url_file = os.path.join(C.RESOURCES_TPL_HC, "config_topology.url")
42         with open(url_file) as template:
43             path = template.readline()
44
45         data = []
46         for node in nodes.values():
47             if node['type'] == NodeType.DUT:
48                 _, ret = HTTPRequest.get(node, path)
49                 logger.debug('return: {0}'.format(ret))
50                 data.append(self.parse_json_response(ret, ("topology",
51                                                            "node", "node-id")))
52
53         return data
54
55     def parse_json_response(self, response, path=None):
56         """Parse data from response string in JSON format according to given
57         path.
58
59         :param response: JSON formatted string
60         :param path: Path to navigate down the data structure
61         :type response: string
62         :type path: tuple
63         :return: JSON dictionary/list tree
64         :rtype: dict
65         """
66         data = loads(response)
67
68         if path:
69             data = self._parse_json_tree(data, path)
70             while isinstance(data, list) and len(data) == 1:
71                 data = data[0]
72
73         return data
74
75     def _parse_json_tree(self, data, path):
76         """Retrieve data from python representation of JSON object.
77
78         :param data: parsed JSON dictionary tree
79         :param path: Path to navigate down the dictionary tree
80         :type data: dict
81         :type path: tuple
82         :return: data from specified path
83         :rtype: list or str
84         """
85
86         count = 0
87         for key in path:
88             if isinstance(data, dict):
89                 data = data[key]
90                 count += 1
91             elif isinstance(data, list):
92                 result = []
93                 for item in data:
94                     result.append(self._parse_json_tree(item, path[count:]))
95                     return result
96
97         return data