Honeycomb interface state management test
[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_duts(*nodes):
45         """Start Honeycomb on specified DUT nodes.
46
47         This keyword starts the Honeycomb service on specified DUTs.
48         The keyword just starts the Honeycomb and does not check its startup
49         state. Use the keyword "Check Honeycomb Startup State" to check if the
50         Honeycomb is up and running.
51         Honeycomb must be installed in "/opt" directory, otherwise the start
52         will fail.
53         :param nodes: List of nodes to start Honeycomb on.
54         :type nodes: list
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:
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_duts(*nodes):
75         """Stop the Honeycomb service on specified DUT nodes.
76
77         This keyword stops the Honeycomb service on specified nodes. It just
78         stops the Honeycomb and does not check its shutdown state. Use the
79         keyword "Check Honeycomb Shutdown State" to check if Honeycomb has
80         stopped.
81         :param nodes: List of nodes to stop Honeycomb on.
82         :type nodes: list
83         :raises HoneycombError: If Honeycomb failed to stop.
84         """
85         logger.console("Shutting down Honeycomb service ...")
86
87         cmd = "{0}/stop".format(Const.REMOTE_HC_DIR)
88         errors = []
89
90         for node in nodes:
91             if node['type'] == NodeType.DUT:
92                 ssh = SSH()
93                 ssh.connect(node)
94                 (ret_code, _, _) = ssh.exec_command_sudo(cmd)
95                 if int(ret_code) != 0:
96                     errors.append(node['host'])
97                 else:
98                     logger.info("Stopping the Honeycomb service on node {0} is "
99                                 "in progress ...".format(node['host']))
100         if errors:
101             raise HoneycombError('Node(s) {0} failed to stop Honeycomb.'.
102                                  format(errors))
103
104     @staticmethod
105     def check_honeycomb_startup_state(*nodes):
106         """Check state of Honeycomb service during startup on specified nodes.
107
108         Reads html path from template file oper_vpp_version.url.
109
110         Honeycomb nodes reply with connection refused or the following status
111         codes depending on startup progress: codes 200, 401, 403, 404, 500, 503
112
113         :param nodes: List of DUT nodes starting Honeycomb.
114         :type nodes: list
115         :return: True if all GETs returned code 200(OK).
116         :rtype bool
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                                  HTTPCodes.INTERNAL_SERVER_ERROR)
124
125         for node in nodes:
126             if node['type'] == NodeType.DUT:
127                 status_code, _ = HTTPRequest.get(node, path, timeout=10,
128                                                  enable_logging=False)
129                 if status_code == HTTPCodes.OK:
130                     logger.info("Honeycomb on node {0} is up and running".
131                                 format(node['host']))
132                 elif status_code in expected_status_codes:
133                     if status_code == HTTPCodes.UNAUTHORIZED:
134                         logger.info('Unauthorized. If this triggers keyword '
135                                     'timeout, verify Honeycomb username and '
136                                     'password.')
137                     raise HoneycombError('Honeycomb on node {0} running but '
138                                          'not yet ready.'.format(node['host']),
139                                          enable_logging=False)
140                 else:
141                     raise HoneycombError('Unexpected return code: {0}.'.
142                                          format(status_code))
143         return True
144
145     @staticmethod
146     def check_honeycomb_shutdown_state(*nodes):
147         """Check state of Honeycomb service during shutdown on specified nodes.
148
149         Honeycomb nodes reply with connection refused or the following status
150         codes depending on shutdown progress: codes 200, 404.
151
152         :param nodes: List of DUT nodes stopping Honeycomb.
153         :type nodes: list
154         :return: True if all GETs fail to connect.
155         :rtype bool
156         """
157         cmd = "ps -ef | grep -v grep | grep karaf"
158         for node in nodes:
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         path = HcUtil.read_path_from_url_file("config_topology_node")
241         try:
242             xml_data = ET.parse("{0}/add_vpp_to_topology.xml".
243                                 format(Const.RESOURCES_TPL_HC))
244         except ET.ParseError as err:
245             raise HoneycombError(repr(err))
246         data = ET.tostring(xml_data.getroot())
247
248         headers = {"Content-Type": "application/xml"}
249
250         status_codes = []
251         responses = []
252         for node_name, node in nodes.items():
253             if node['type'] == NodeType.DUT:
254                 try:
255                     payload = data.format(
256                         vpp_host=node_name,
257                         vpp_ip=node["host"],
258                         vpp_port=node['honeycomb']["netconf_port"],
259                         user=node['honeycomb']["user"],
260                         passwd=node['honeycomb']["passwd"])
261                     status_code, resp = HTTPRequest.put(
262                         node=node,
263                         path="{0}/{1}".format(path, node_name),
264                         headers=headers,
265                         payload=payload)
266                     if status_code != HTTPCodes.OK:
267                         raise HoneycombError(
268                             "VPP {0} was not added to topology. "
269                             "Status code: {1}.".format(node["host"],
270                                                        status_code))
271
272                     status_codes.append(status_code)
273                     responses.append(resp)
274
275                 except HTTPRequestError as err:
276                     raise HoneycombError("VPP {0} was not added to topology.".
277                                          format(node["host"]), repr(err))
278         return status_codes, responses