1 # Copyright (c) 2017 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:
6 # http://www.apache.org/licenses/LICENSE-2.0
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.
14 """Implementation of keywords for Honeycomb setup."""
16 from json import loads
17 from time import time, sleep
19 from ipaddress import IPv6Address, AddressValueError
21 from robot.api import logger
23 from resources.libraries.python.HTTPRequest import HTTPRequest, HTTPCodes, \
25 from resources.libraries.python.constants import Constants as Const
26 from resources.libraries.python.honeycomb.HoneycombUtil import HoneycombError
27 from resources.libraries.python.honeycomb.HoneycombUtil \
28 import HoneycombUtil as HcUtil
29 from resources.libraries.python.ssh import SSH
30 from resources.libraries.python.topology import NodeType
33 class HoneycombSetup(object):
34 """Implements keywords for Honeycomb setup.
36 The keywords implemented in this class make possible to:
39 - check the Honeycomb start-up state,
40 - check the Honeycomb shutdown state,
41 - add VPP to the topology.
48 def start_honeycomb_on_duts(*nodes):
49 """Start Honeycomb on specified DUT nodes.
51 This keyword starts the Honeycomb service on specified DUTs.
52 The keyword just starts the Honeycomb and does not check its startup
53 state. Use the keyword "Check Honeycomb Startup State" to check if the
54 Honeycomb is up and running.
55 Honeycomb must be installed in "/opt" directory, otherwise the start
57 :param nodes: List of nodes to start Honeycomb on.
59 :raises HoneycombError: If Honeycomb fails to start.
62 HoneycombSetup.print_environment(nodes)
64 logger.console("\n(re)Starting Honeycomb service ...")
66 cmd = "sudo service honeycomb start"
69 if node['type'] == NodeType.DUT:
72 (ret_code, _, _) = ssh.exec_command_sudo(cmd)
73 if int(ret_code) != 0:
74 raise HoneycombError('Node {0} failed to start Honeycomb.'.
77 logger.info("Starting the Honeycomb service on node {0} is "
78 "in progress ...".format(node['host']))
81 def stop_honeycomb_on_duts(*nodes):
82 """Stop the Honeycomb service on specified DUT nodes.
84 This keyword stops the Honeycomb service on specified nodes. It just
85 stops the Honeycomb and does not check its shutdown state. Use the
86 keyword "Check Honeycomb Shutdown State" to check if Honeycomb has
88 :param nodes: List of nodes to stop Honeycomb on.
90 :raises HoneycombError: If Honeycomb failed to stop.
92 logger.console("\nShutting down Honeycomb service ...")
94 cmd = "sudo service honeycomb stop"
98 if node['type'] == NodeType.DUT:
101 (ret_code, _, _) = ssh.exec_command_sudo(cmd)
102 if int(ret_code) != 0:
103 errors.append(node['host'])
105 logger.info("Stopping the Honeycomb service on node {0} is "
106 "in progress ...".format(node['host']))
108 raise HoneycombError('Node(s) {0} failed to stop Honeycomb.'.
112 def restart_honeycomb_on_dut(node):
113 """Restart Honeycomb on specified DUT nodes.
115 This keyword restarts the Honeycomb service on specified DUTs. Use the
116 keyword "Check Honeycomb Startup State" to check if the Honeycomb is up
119 :param node: Node to restart Honeycomb on.
121 :raises HoneycombError: If Honeycomb fails to start.
124 logger.console("\n(re)Starting Honeycomb service ...")
126 cmd = "sudo service honeycomb restart"
130 (ret_code, _, _) = ssh.exec_command_sudo(cmd)
131 if int(ret_code) != 0:
132 raise HoneycombError('Node {0} failed to restart Honeycomb.'.
133 format(node['host']))
136 "Honeycomb service restart is in progress on node {0}".format(
140 def check_honeycomb_startup_state(node, timeout=360, retries=20,
142 """Repeatedly check the status of Honeycomb startup until it is fully
143 started or until timeout or max retries is reached.
145 :param node: Honeycomb node.
146 :param timeout: Timeout value in seconds.
147 :param retries: Max number of retries.
148 :param interval: Interval between checks, in seconds.
153 :raises HoneycombError: If the Honeycomb process IP cannot be found,
154 or if timeout or number of retries is exceeded."""
161 while time() - start < timeout and count < retries:
165 status_code_version, _ = HcUtil.get_honeycomb_data(
166 node, "oper_vpp_version")
167 status_code_if_cfg, _ = HcUtil.get_honeycomb_data(
168 node, "config_vpp_interfaces")
169 status_code_if_oper, _ = HcUtil.get_honeycomb_data(
170 node, "oper_vpp_interfaces")
171 except HTTPRequestError:
174 if status_code_if_cfg == HTTPCodes.OK\
175 and status_code_if_cfg == HTTPCodes.OK\
176 and status_code_if_oper == HTTPCodes.OK:
177 logger.info("Check successful, Honeycomb is up and running.")
181 "Attempt ${count} failed on Restconf check. Status codes:\n"
182 "Version: {version}\n"
183 "Interface config: {if_cfg}\n"
184 "Interface operational: {if_oper}".format(
186 version=status_code_version,
187 if_cfg=status_code_if_cfg,
188 if_oper=status_code_if_oper))
192 _, vpp_status, _ = ssh.exec_command("sudo service vpp status")
193 raise HoneycombError(
194 "Timeout or max retries exceeded. Status of VPP:\n"
195 "{vpp_status}".format(vpp_status=vpp_status))
198 def check_honeycomb_shutdown_state(node):
199 """Check state of Honeycomb service during shutdown on specified nodes.
201 Honeycomb nodes reply with connection refused or the following status
202 codes depending on shutdown progress: codes 200, 404.
204 :param node: List of DUT nodes stopping Honeycomb.
206 :return: True if all GETs fail to connect.
209 cmd = "pgrep honeycomb"
213 (ret_code, _, _) = ssh.exec_command_sudo(cmd)
215 raise HoneycombError('Honeycomb on node {0} is still '
216 'running.'.format(node['host']),
217 enable_logging=False)
219 logger.info("Honeycomb on node {0} has stopped".
220 format(node['host']))
224 def configure_restconf_binding_address(node):
225 """Configure Honeycomb to accept restconf requests from all IP
226 addresses. IP version is determined by node data.
228 :param node: Information about a DUT node.
230 :raises HoneycombError: If the configuration could not be changed.
233 find = "restconf-binding-address"
235 IPv6Address(unicode(node["host"]))
236 # if management IP of the node is in IPv6 format
237 replace = '\\"restconf-binding-address\\": \\"0::0\\",'
238 except (AttributeError, AddressValueError):
239 replace = '\\"restconf-binding-address\\": \\"0.0.0.0\\",'
241 argument = '"/{0}/c\\ {1}"'.format(find, replace)
242 path = "{0}/config/restconf.json".format(Const.REMOTE_HC_DIR)
243 command = "sed -i {0} {1}".format(argument, path)
247 (ret_code, _, stderr) = ssh.exec_command_sudo(command)
249 raise HoneycombError("Failed to modify configuration on "
250 "node {0}, {1}".format(node, stderr))
253 def configure_jvpp_timeout(node, timeout=10):
254 """Configure timeout value for Java API commands Honeycomb sends to VPP.
256 :param node: Information about a DUT node.
257 :param timeout: Timeout value in seconds.
260 :raises HoneycombError: If the configuration could not be changed.
263 find = "jvpp-request-timeout"
264 replace = '\\"jvpp-request-timeout\\": {0}'.format(timeout)
266 argument = '"/{0}/c\\ {1}"'.format(find, replace)
267 path = "{0}/config/jvpp.json".format(Const.REMOTE_HC_DIR)
268 command = "sed -i {0} {1}".format(argument, path)
272 (ret_code, _, stderr) = ssh.exec_command_sudo(command)
274 raise HoneycombError("Failed to modify configuration on "
275 "node {0}, {1}".format(node, stderr))
278 def print_environment(nodes):
279 """Print information about the nodes to log. The information is defined
280 by commands in cmds tuple at the beginning of this method.
282 :param nodes: List of DUT nodes to get information about.
286 # TODO: When everything is set and running in VIRL env, transform this
287 # method to a keyword checking the environment.
295 "dpkg --list | grep openjdk",
296 "ls -la /opt/honeycomb")
299 if node['type'] == NodeType.DUT:
300 logger.info("Checking node {} ...".format(node['host']))
302 logger.info("Command: {}".format(cmd))
305 ssh.exec_command_sudo(cmd)
308 def print_ports(node):
309 """Uses "sudo netstat -anp | grep java" to print port where a java
312 :param node: Honeycomb node where we want to print the ports.
316 cmds = ("netstat -anp | grep java",
317 "ps -ef | grep [h]oneycomb")
319 logger.info("Checking node {} ...".format(node['host']))
321 logger.info("Command: {}".format(cmd))
324 ssh.exec_command_sudo(cmd)
327 def configure_log_level(node, level):
328 """Set Honeycomb logging to the specified level.
330 :param node: Honeycomb node.
331 :param level: Log level (INFO, DEBUG, TRACE).
336 find = 'logger name=\\"io.fd\\"'
337 replace = '<logger name=\\"io.fd\\" level=\\"{0}\\"/>'.format(level)
339 argument = '"/{0}/c\\ {1}"'.format(find, replace)
340 path = "{0}/config/logback.xml".format(Const.REMOTE_HC_DIR)
341 command = "sed -i {0} {1}".format(argument, path)
345 (ret_code, _, stderr) = ssh.exec_command_sudo(command)
347 raise HoneycombError("Failed to modify configuration on "
348 "node {0}, {1}".format(node, stderr))
351 def manage_honeycomb_features(node, feature, disable=False):
352 """Configure Honeycomb to use features that are disabled by default, or
353 disable previously enabled features.
355 ..Note:: If the module is not enabled in VPP, Honeycomb will
356 be unable to establish VPP connection.
358 :param node: Honeycomb node.
359 :param feature: Feature to enable.
360 :param disable: Disable the specified feature instead of enabling it.
362 :type feature: string
364 :raises HoneycombError: If the configuration could not be changed.
367 disabled_features = {
368 "NSH": "io.fd.hc2vpp.vppnsh.impl.VppNshModule"
374 if feature in disabled_features.keys():
375 # uncomment by replacing the entire line
376 find = replace = "{0}".format(disabled_features[feature])
378 replace = "// {0}".format(find)
380 argument = '"/{0}/c\\ {1}"'.format(find, replace)
381 path = "{0}/modules/*module-config"\
382 .format(Const.REMOTE_HC_DIR)
383 command = "sed -i {0} {1}".format(argument, path)
385 (ret_code, _, stderr) = ssh.exec_command_sudo(command)
387 raise HoneycombError("Failed to modify configuration on "
388 "node {0}, {1}".format(node, stderr))
390 raise HoneycombError(
391 "Unrecognized feature {0}.".format(feature))
394 def copy_java_libraries(node):
395 """Copy Java libraries installed by vpp-api-java package to honeycomb
398 This is a (temporary?) workaround for jvpp version mismatches.
400 :param node: Honeycomb node
406 (_, stdout, _) = ssh.exec_command_sudo(
407 "ls /usr/share/java | grep ^jvpp-*")
409 files = stdout.split("\n")[:-1]
412 # jvpp-registry-17.04.jar
413 # jvpp-core-17.04.jar
415 parts = item.split("-")
416 version = "{0}-SNAPSHOT".format(parts[2][:5])
417 artifact_id = "{0}-{1}".format(parts[0], parts[1])
419 directory = "{0}/lib/io/fd/vpp/{1}/{2}".format(
420 Const.REMOTE_HC_DIR, artifact_id, version)
421 cmd = "sudo mkdir -p {0}; " \
422 "sudo cp /usr/share/java/{1} {0}/{2}-{3}.jar".format(
423 directory, item, artifact_id, version)
425 (ret_code, _, stderr) = ssh.exec_command(cmd)
427 raise HoneycombError("Failed to copy JVPP libraries on "
428 "node {0}, {1}".format(node, stderr))
431 def copy_odl_client(node, odl_name, src_path, dst_path):
432 """Copy ODL Client from source path to destination path.
434 :param node: Honeycomb node.
435 :param odl_name: Name of ODL client version to use.
436 :param src_path: Source Path where to find ODl client.
437 :param dst_path: Destination path.
442 :raises HoneycombError: If the operation fails.
448 cmd = "sudo rm -rf {dst}/*karaf_{odl_name} && " \
449 "cp -r {src}/*karaf_{odl_name}* {dst}".format(
450 src=src_path, odl_name=odl_name, dst=dst_path)
452 ret_code, _, _ = ssh.exec_command_sudo(cmd, timeout=180)
453 if int(ret_code) != 0:
454 raise HoneycombError(
455 "Failed to copy ODL client on node {0}".format(node["host"]))
458 def setup_odl_client(node, path):
459 """Start ODL client on the specified node.
461 Karaf should be located in the provided path, and VPP and Honeycomb
462 should already be running, otherwise the start will fail.
463 :param node: Node to start ODL client on.
464 :param path: Path to ODL client on node.
467 :raises HoneycombError: If Honeycomb fails to start.
470 logger.console("\nStarting ODL client ...")
474 cmd = "{path}/*karaf*/bin/start clean".format(path=path)
475 ret_code, _, _ = ssh.exec_command_sudo(cmd)
477 if int(ret_code) != 0:
478 raise HoneycombError('Node {0} failed to start ODL.'.
479 format(node['host']))
481 logger.info("Starting the ODL client on node {0} is "
482 "in progress ...".format(node['host']))
485 def install_odl_features(node, path, *features):
486 """Install required features on a running ODL client.
488 :param node: Honeycomb node.
489 :param path: Path to ODL client on node.
490 :param features: Optional, list of additional features to install.
499 cmd = "{path}/*karaf*/bin/client -u karaf feature:install " \
500 "odl-restconf-all " \
501 "odl-netconf-connector-all " \
502 "odl-netconf-topology".format(path=path)
503 for feature in features:
504 cmd += " {0}".format(feature)
506 ret_code, _, _ = ssh.exec_command_sudo(cmd, timeout=250)
508 if int(ret_code) != 0:
509 raise HoneycombError("Feature install did not succeed.")
512 def check_odl_startup_state(node):
513 """Check the status of ODL client startup.
515 :param node: Honeycomb node.
517 :returns: True when ODL is started.
519 :raises HoneycombError: When the response is not code 200: OK.
522 path = HcUtil.read_path_from_url_file(
523 "odl_client/odl_netconf_connector")
524 expected_status_codes = (HTTPCodes.UNAUTHORIZED,
527 HTTPCodes.SERVICE_UNAVAILABLE,
528 HTTPCodes.INTERNAL_SERVER_ERROR)
530 status_code, _ = HTTPRequest.get(node, path, timeout=10,
531 enable_logging=False)
532 if status_code == HTTPCodes.OK:
533 logger.info("ODL client on node {0} is up and running".
534 format(node['host']))
535 elif status_code in expected_status_codes:
536 if status_code == HTTPCodes.UNAUTHORIZED:
537 logger.info('Unauthorized. If this triggers keyword '
538 'timeout, verify username and password.')
539 raise HoneycombError('ODL client on node {0} running but '
540 'not yet ready.'.format(node['host']),
541 enable_logging=False)
543 raise HoneycombError('Unexpected return code: {0}.'.
548 def check_odl_shutdown_state(node):
549 """Check the status of ODL client shutdown.
551 :param node: Honeycomb node.
553 :returns: True when ODL is stopped.
555 :raises HoneycombError: When the response is not code 200: OK.
558 cmd = "pgrep -f karaf"
559 path = HcUtil.read_path_from_url_file(
560 "odl_client/odl_netconf_connector")
563 HTTPRequest.get(node, path, timeout=10, enable_logging=False)
564 raise HoneycombError("ODL client is still running.")
565 except HTTPRequestError:
566 logger.debug("Connection refused, checking process state....")
569 ret_code, _, _ = ssh.exec_command(cmd)
571 raise HoneycombError("ODL client is still running.")
576 def mount_honeycomb_on_odl(node):
577 """Tell ODL client to mount Honeycomb instance over netconf.
579 :param node: Honeycomb node.
581 :raises HoneycombError: When the response is not code 200: OK.
584 path = HcUtil.read_path_from_url_file(
585 "odl_client/odl_netconf_connector")
587 url_file = "{0}/{1}".format(Const.RESOURCES_TPL_HC,
588 "odl_client/mount_honeycomb.json")
590 with open(url_file) as template:
591 data = template.read()
595 status_code, _ = HTTPRequest.post(
598 headers={"Content-Type": "application/json",
599 "Accept": "text/plain"},
602 enable_logging=False)
604 if status_code == HTTPCodes.OK:
605 logger.info("ODL mount point configured successfully.")
606 elif status_code == HTTPCodes.CONFLICT:
607 logger.info("ODL mount point was already configured.")
609 raise HoneycombError('Mount point configuration not successful')
612 def stop_odl_client(node, path):
613 """Stop ODL client service on the specified node.
615 :param node: Node to start ODL client on.
616 :param path: Path to ODL client.
619 :raises HoneycombError: If ODL client fails to stop.
625 cmd = "{0}/*karaf*/bin/stop".format(path)
629 ret_code, _, _ = ssh.exec_command_sudo(cmd)
630 if int(ret_code) != 0:
631 logger.debug("ODL Client refused to shut down.")
632 cmd = "pkill -f 'karaf'"
633 (ret_code, _, _) = ssh.exec_command_sudo(cmd)
634 if int(ret_code) != 0:
635 raise HoneycombError('Node {0} failed to stop ODL.'.
636 format(node['host']))
638 logger.info("ODL client service stopped.")
642 class HoneycombStartupConfig(object):
643 """Generator for Honeycomb startup configuration.
648 self.template = """#!/bin/sh -
651 while [ $STATUS -eq 100 ]
653 {java_call} -jar $(dirname $0)/{jar_filename}
655 echo "Honeycomb exited with status: $STATUS"
656 if [ $STATUS -eq 100 ]
663 self.java_call = "{scheduler} {affinity} java{jit_mode}{params}"
666 self.core_affinity = ""
674 def apply_config(self, node):
675 """Generate configuration file /opt/honeycomb/honeycomb on the specified
678 :param node: Honeycomb node.
682 self.ssh.connect(node)
683 _, filename, _ = self.ssh.exec_command("ls /opt/honeycomb | grep .jar")
685 java_call = self.java_call.format(scheduler=self.scheduler,
686 affinity=self.core_affinity,
687 jit_mode=self.jit_mode,
689 self.config = self.template.format(java_call=java_call,
690 jar_filename=filename)
692 self.ssh.connect(node)
693 cmd = "echo '{config}' > /tmp/honeycomb " \
694 "&& chmod +x /tmp/honeycomb " \
695 "&& sudo mv -f /tmp/honeycomb /opt/honeycomb".\
696 format(config=self.config)
697 self.ssh.exec_command(cmd)
699 def set_cpu_scheduler(self, scheduler="FIFO"):
700 """Use alternate CPU scheduler.
702 Note: OTHER scheduler doesn't load-balance over isolcpus.
704 :param scheduler: CPU scheduler to use.
708 schedulers = {"FIFO": "-f 99", # First In, First Out
709 "RR": "-r 99", # Round Robin
710 "OTHER": "-o", # Ubuntu default
712 self.scheduler = "chrt {0}".format(schedulers[scheduler])
714 def set_cpu_core_affinity(self, low, high=None):
715 """Set core affinity for the honeycomb process and subprocesses.
717 :param low: Lowest core ID number.
718 :param high: Highest core ID number. Leave empty to use a single core.
723 self.core_affinity = "taskset -c {low}-{high}".format(
724 low=low, high=high if high else low)
726 def set_jit_compiler_mode(self, jit_mode):
727 """Set running mode for Java's JIT compiler.
729 :param jit_mode: Desiret JIT mode.
733 modes = {"client": " -client", # Default
734 "server": " -server", # Higher performance but longer warmup
735 "classic": " -classic" # Disables JIT compiler
738 self.jit_mode = modes[jit_mode]
740 def set_memory_size(self, mem_min, mem_max=None):
741 """Set minimum and maximum memory use for the JVM.
743 :param mem_min: Minimum amount of memory (MB).
744 :param mem_max: Maximum amount of memory (MB). Default is 4 times
750 self.params += " -Xms{min}m -Xmx{max}m".format(
751 min=mem_min, max=mem_max if mem_max else mem_min*4)
753 def set_metaspace_size(self, mem_min, mem_max=None):
754 """Set minimum and maximum memory used for class metadata in the JVM.
756 :param mem_min: Minimum metaspace size (MB).
757 :param mem_max: Maximum metaspace size (MB). Defailt is 4 times
763 self.params += " -XX:MetaspaceSize={min}m " \
764 "-XX:MaxMetaspaceSize={max}m".format(
765 min=mem_min, max=mem_max if mem_max else mem_min*4)
767 def set_numa_optimization(self):
768 """Use optimization of memory use and garbage collection for NUMA
771 self.params += " -XX:+UseNUMA -XX:+UseParallelGC"
773 def set_ssh_security_provider(self):
774 """Disables BouncyCastle for SSHD."""
775 # Workaround for issue described in:
776 # https://wiki.fd.io/view/Honeycomb/Releases/1609/Honeycomb_and_ODL
778 self.params += " -Dorg.apache.sshd.registerBouncyCastle=false"