Honeycomb setup and utils
[csit.git] / resources / libraries / python / HoneycombSetup.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 """Implementation of keywords for Honeycomb setup."""
15
16 from xml.etree import ElementTree as ET
17
18 from robot.api import logger
19
20 from resources.libraries.python.topology import NodeType
21 from resources.libraries.python.ssh import SSH
22 from resources.libraries.python.HTTPRequest import HTTPRequest, HTTPCodes, \
23     HTTPRequestError
24 from resources.libraries.python.HoneycombUtil import HoneycombUtil as HcUtil
25 from resources.libraries.python.HoneycombUtil import HoneycombError
26 from resources.libraries.python.constants import Constants as Const
27
28
29 class HoneycombSetup(object):
30     """Implements keywords for Honeycomb setup.
31
32     The keywords implemented in this class make possible to:
33     - start Honeycomb,
34     - stop Honeycomb,
35     - check the Honeycomb start-up state,
36     - check the Honeycomb shutdown state,
37     - add VPP to the topology.
38     """
39
40     def __init__(self):
41         pass
42
43     @staticmethod
44     def start_honeycomb_on_all_duts(nodes):
45         """Start Honeycomb on all DUT nodes in topology.
46
47         This keyword starts the Honeycomb service on all DUTs. The keyword just
48         starts the Honeycomb and does not check its startup state. Use the
49         keyword "Check Honeycomb Startup State" to check if the Honeycomb is up
50         and running.
51         Honeycomb must be installed in "/opt" directory, otherwise the start
52         will fail.
53         :param nodes: All nodes in topology.
54         :type nodes: dict
55         :raises HoneycombError: If Honeycomb fails to start.
56         """
57         logger.console("Starting Honeycomb service ...")
58
59         cmd = "{0}/start".format(Const.REMOTE_HC_DIR)
60
61         for node in nodes.values():
62             if node['type'] == NodeType.DUT:
63                 ssh = SSH()
64                 ssh.connect(node)
65                 (ret_code, _, _) = ssh.exec_command_sudo(cmd)
66                 if int(ret_code) != 0:
67                     raise HoneycombError('Node {0} failed to start Honeycomb.'.
68                                          format(node['host']))
69                 else:
70                     logger.info("Starting the Honeycomb service on node {0} is "
71                                 "in progress ...".format(node['host']))
72
73     @staticmethod
74     def stop_honeycomb_on_all_duts(nodes):
75         """Stop the Honeycomb service on all DUTs.
76
77         This keyword stops the Honeycomb service on all nodes. It just stops the
78         Honeycomb and does not check its shutdown state. Use the keyword "Check
79         Honeycomb Shutdown State" to check if Honeycomb has stopped.
80         :param nodes: Nodes in topology.
81         :type nodes: dict
82         :raises HoneycombError: If Honeycomb failed to stop.
83         """
84         logger.console("Shutting down Honeycomb service ...")
85
86         cmd = "{0}/stop".format(Const.REMOTE_HC_DIR)
87         errors = []
88
89         for node in nodes.values():
90             if node['type'] == NodeType.DUT:
91                 ssh = SSH()
92                 ssh.connect(node)
93                 (ret_code, _, _) = ssh.exec_command_sudo(cmd)
94                 if int(ret_code) != 0:
95                     errors.append(node['host'])
96                 else:
97                     logger.info("Stopping the Honeycomb service on node {0} is "
98                                 "in progress ...".format(node['host']))
99         if errors:
100             raise HoneycombError('Node(s) {0} failed to stop Honeycomb.'.
101                                  format(errors))
102
103     @staticmethod
104     def check_honeycomb_startup_state(nodes):
105         """Check state of Honeycomb service during startup.
106
107         Reads html path from template file oper_vpp_version.url.
108
109         Honeycomb node replies with connection refused or the following status
110         codes depending on startup progress: codes 200, 401, 403, 404, 503
111
112         :param nodes: Nodes in topology.
113         :type nodes: dict
114         :return: True if all GETs returned code 200(OK).
115         :rtype bool
116         """
117
118         path = HcUtil.read_path_from_url_file("oper_vpp_version")
119         expected_status_codes = (HTTPCodes.UNAUTHORIZED,
120                                  HTTPCodes.FORBIDDEN,
121                                  HTTPCodes.NOT_FOUND,
122                                  HTTPCodes.SERVICE_UNAVAILABLE)
123
124         for node in nodes.values():
125             if node['type'] == NodeType.DUT:
126                 status_code, _ = HTTPRequest.get(node, path, timeout=10,
127                                                  enable_logging=False)
128                 if status_code == HTTPCodes.OK:
129                     logger.info("Honeycomb on node {0} is up and running".
130                                 format(node['host']))
131                 elif status_code in expected_status_codes:
132                     if status_code == HTTPCodes.UNAUTHORIZED:
133                         logger.info('Unauthorized. If this triggers keyword '
134                                     'timeout, verify Honeycomb username and '
135                                     'password.')
136                     raise HoneycombError('Honeycomb on node {0} running but '
137                                          'not yet ready.'.format(node['host']),
138                                          enable_logging=False)
139                 else:
140                     raise HoneycombError('Unexpected return code: {0}.'.
141                                          format(status_code))
142         return True
143
144     @staticmethod
145     def check_honeycomb_shutdown_state(nodes):
146         """Check state of Honeycomb service during shutdown.
147
148         Honeycomb node replies with connection refused or the following status
149         codes depending on shutdown progress: codes 200, 404.
150
151         :param nodes: Nodes in topology.
152         :type nodes: dict
153         :return: True if all GETs fail to connect.
154         :rtype bool
155         """
156
157         cmd = "ps -ef | grep -v grep | grep karaf"
158         for node in nodes.values():
159             if node['type'] == NodeType.DUT:
160                 try:
161                     status_code, _ = HTTPRequest.get(node, '/index.html',
162                                                      timeout=5,
163                                                      enable_logging=False)
164                     if status_code == HTTPCodes.OK:
165                         raise HoneycombError('Honeycomb on node {0} is still '
166                                              'running.'.format(node['host']),
167                                              enable_logging=False)
168                     elif status_code == HTTPCodes.NOT_FOUND:
169                         raise HoneycombError('Honeycomb on node {0} is shutting'
170                                              ' down.'.format(node['host']),
171                                              enable_logging=False)
172                     else:
173                         raise HoneycombError('Unexpected return code: {0}.'.
174                                              format(status_code))
175                 except HTTPRequestError:
176                     logger.debug('Connection refused, checking the process '
177                                  'state ...')
178                     ssh = SSH()
179                     ssh.connect(node)
180                     (ret_code, _, _) = ssh.exec_command_sudo(cmd)
181                     if ret_code == 0:
182                         raise HoneycombError('Honeycomb on node {0} is still '
183                                              'running.'.format(node['host']),
184                                              enable_logging=False)
185                     else:
186                         logger.info("Honeycomb on node {0} has stopped".
187                                     format(node['host']))
188         return True
189
190     @staticmethod
191     def add_vpp_to_honeycomb_network_topology(nodes):
192         """Add vpp node to Honeycomb network topology.
193
194         :param nodes: All nodes in test topology.
195         :type nodes: dict
196         :return: Status code and response content from PUT requests.
197         :rtype: tuple
198         :raises HoneycombError: If a node was not added to Honeycomb topology.
199
200         Reads HTML path from template file config_topology_node.url.
201         Path to the node to be added, e.g.:
202         ("/restconf/config/network-topology:network-topology"
203          "/topology/topology-netconf/node/")
204         There must be "/" at the end, as generated node name is added at the
205         end.
206
207         Reads payload data from template file add_vpp_to_topology.xml.
208         Information about node as XML structure, e.g.:
209         <node xmlns="urn:TBD:params:xml:ns:yang:network-topology">
210             <node-id>
211                 {vpp_host}
212             </node-id>
213             <host xmlns="urn:opendaylight:netconf-node-topology">
214                 {vpp_ip}
215             </host>
216             <port xmlns="urn:opendaylight:netconf-node-topology">
217                 {vpp_port}
218             </port>
219             <username xmlns="urn:opendaylight:netconf-node-topology">
220                 {user}
221             </username>
222             <password xmlns="urn:opendaylight:netconf-node-topology">
223                 {passwd}
224             </password>
225             <tcp-only xmlns="urn:opendaylight:netconf-node-topology">
226                 false
227             </tcp-only>
228             <keepalive-delay xmlns="urn:opendaylight:netconf-node-topology">
229                 0
230             </keepalive-delay>
231         </node>
232         NOTE: The placeholders:
233             {vpp_host}
234             {vpp_ip}
235             {vpp_port}
236             {user}
237             {passwd}
238         MUST be there as they are replaced by correct values.
239         """
240
241         path = HcUtil.read_path_from_url_file("config_topology_node")
242         try:
243             xml_data = ET.parse("{0}/add_vpp_to_topology.xml".
244                                 format(Const.RESOURCES_TPL_HC))
245         except ET.ParseError as err:
246             raise HoneycombError(repr(err))
247         data = ET.tostring(xml_data.getroot())
248
249         headers = {"Content-Type": "application/xml"}
250
251         status_codes = []
252         responses = []
253         for node_name, node in nodes.items():
254             if node['type'] == NodeType.DUT:
255                 try:
256                     payload = data.format(
257                         vpp_host=node_name,
258                         vpp_ip=node["host"],
259                         vpp_port=node['honeycomb']["netconf_port"],
260                         user=node['honeycomb']["user"],
261                         passwd=node['honeycomb']["passwd"])
262                     status_code, resp = HTTPRequest.put(
263                         node=node,
264                         path="{0}/{1}".format(path, node_name),
265                         headers=headers,
266                         payload=payload)
267                     if status_code != HTTPCodes.OK:
268                         raise HoneycombError(
269                             "VPP {0} was not added to topology. "
270                             "Status code: {1}.".format(node["host"],
271                                                        status_code))
272
273                     status_codes.append(status_code)
274                     responses.append(resp)
275
276                 except HTTPRequestError as err:
277                     raise HoneycombError("VPP {0} was not added to topology.".
278                                          format(node["host"]), repr(err))
279         return status_codes, responses