コード例 #1
0
    def check_odl_startup_state(node):
        """Check the status of ODL client startup.

        :param node: Honeycomb node.
        :param node: dict
        :returns: True when ODL is started.
        :rtype: bool
        :raises HoneycombError: When the response is not code 200: OK.
        """

        path = HcUtil.read_path_from_url_file(
            "odl_client/odl_netconf_connector")
        expected_status_codes = (HTTPCodes.UNAUTHORIZED, HTTPCodes.FORBIDDEN,
                                 HTTPCodes.NOT_FOUND,
                                 HTTPCodes.SERVICE_UNAVAILABLE,
                                 HTTPCodes.INTERNAL_SERVER_ERROR)

        status_code, _ = HTTPRequest.get(node,
                                         path,
                                         timeout=10,
                                         enable_logging=False)
        if status_code == HTTPCodes.OK:
            logger.info("ODL client on node {0} is up and running".format(
                node['host']))
        elif status_code in expected_status_codes:
            if status_code == HTTPCodes.UNAUTHORIZED:
                logger.info('Unauthorized. If this triggers keyword '
                            'timeout, verify username and password.')
            raise HoneycombError('ODL client on node {0} running but '
                                 'not yet ready.'.format(node['host']),
                                 enable_logging=False)
        else:
            raise HoneycombError(
                'Unexpected return code: {0}.'.format(status_code))
        return True
コード例 #2
0
    def check_odl_shutdown_state(node):
        """Check the status of ODL client shutdown.

        :param node: Honeycomb node.
        :type node: dict
        :returns: True when ODL is stopped.
        :rtype: bool
        :raises HoneycombError: When the response is not code 200: OK.
        """

        cmd = "pgrep -f karaf"
        path = HcUtil.read_path_from_url_file(
            "odl_client/odl_netconf_connector")

        try:
            HTTPRequest.get(node, path, timeout=10, enable_logging=False)
            raise HoneycombError("ODL client is still running.")
        except HTTPRequestError:
            logger.debug("Connection refused, checking process state....")
            ssh = SSH()
            ssh.connect(node)
            ret_code, _, _ = ssh.exec_command(cmd)
            if ret_code == 0:
                raise HoneycombError("ODL client is still running.")

        return True
コード例 #3
0
    def enable_module_features(node, *features):
        """Configure Honeycomb to use VPP modules that are disabled by default.

        ..Note:: If the module is not enabled in VPP, Honeycomb will
        be unable to establish VPP connection.

        :param node: Honeycomb node.
        :param features: Features to enable.
        :type node: dict
        :type features: string
        :raises HoneycombError: If the configuration could not be changed.
         """

        disabled_features = {"NSH": "io.fd.hc2vpp.vppnsh.impl.VppNshModule"}

        ssh = SSH()
        ssh.connect(node)

        for feature in features:
            if feature in disabled_features.keys():
                # uncomment by replacing the entire line
                find = replace = "{0}".format(disabled_features[feature])

                argument = '"/{0}/c\\ {1}"'.format(find, replace)
                path = "{0}/modules/*module-config"\
                    .format(Const.REMOTE_HC_DIR)
                command = "sed -i {0} {1}".format(argument, path)

                (ret_code, _, stderr) = ssh.exec_command_sudo(command)
                if ret_code != 0:
                    raise HoneycombError("Failed to modify configuration on "
                                         "node {0}, {1}".format(node, stderr))
            else:
                raise HoneycombError(
                    "Unrecognized feature {0}.".format(feature))
コード例 #4
0
ファイル: HoneycombSetup.py プロジェクト: krickwix/csit
    def check_honeycomb_startup_state(*nodes):
        """Check state of Honeycomb service during startup on specified nodes.

        Reads html path from template file oper_vpp_version.url.

        Honeycomb nodes reply with connection refused or the following status
        codes depending on startup progress: codes 200, 401, 403, 404, 500, 503

        :param nodes: List of DUT nodes starting Honeycomb.
        :type nodes: list
        :return: True if all GETs returned code 200(OK).
        :rtype bool
        """
        path = HcUtil.read_path_from_url_file("oper_vpp_version")
        expected_status_codes = (HTTPCodes.UNAUTHORIZED, HTTPCodes.FORBIDDEN,
                                 HTTPCodes.NOT_FOUND,
                                 HTTPCodes.SERVICE_UNAVAILABLE,
                                 HTTPCodes.INTERNAL_SERVER_ERROR)

        for node in nodes:
            if node['type'] == NodeType.DUT:
                HoneycombSetup.print_ports(node)
                try:
                    status_code, _ = HTTPRequest.get(node,
                                                     path,
                                                     enable_logging=False)
                except HTTPRequestError:
                    ssh = SSH()
                    ssh.connect(node)
                    ret_code, _, _ = ssh.exec_command_sudo(
                        "tail -n 100 /var/log/syslog")
                    if ret_code != 0:
                        # It's probably Centos
                        ssh.exec_command_sudo("tail -n 100 /var/log/messages")
                    raise
                if status_code == HTTPCodes.OK:
                    logger.info(
                        "Honeycomb on node {0} is up and running".format(
                            node['host']))
                elif status_code in expected_status_codes:
                    if status_code == HTTPCodes.UNAUTHORIZED:
                        logger.info('Unauthorized. If this triggers keyword '
                                    'timeout, verify Honeycomb username and '
                                    'password.')
                    raise HoneycombError('Honeycomb on node {0} running but '
                                         'not yet ready.'.format(node['host']),
                                         enable_logging=False)
                else:
                    raise HoneycombError(
                        'Unexpected return code: {0}.'.format(status_code))

                status_code, _ = HcUtil.get_honeycomb_data(
                    node, "config_vpp_interfaces")
                if status_code != HTTPCodes.OK:
                    raise HoneycombError('Honeycomb on node {0} running but '
                                         'not yet ready.'.format(node['host']),
                                         enable_logging=False)
        return True
コード例 #5
0
    def manage_honeycomb_features(node, feature, disable=False):
        """Configure Honeycomb to use features that are disabled by default, or
        disable previously enabled features.

        ..Note:: If the module is not enabled in VPP, Honeycomb will
        be unable to establish VPP connection.

        :param node: Honeycomb node.
        :param feature: Feature to enable.
        :param disable: Disable the specified feature instead of enabling it.
        :type node: dict
        :type feature: string
        :type disable: bool
        :raises HoneycombError: If the configuration could not be changed.
         """

        disabled_features = {
            "NSH": ["io.fd.hc2vpp.vppnsh.impl.VppNshModule"],
            "BGP": [
                "io.fd.hc2vpp.bgp.inet.BgpInetModule",
                "io.fd.honeycomb.infra.bgp.BgpModule",
                "io.fd.honeycomb.infra.bgp.BgpReadersModule",
                "io.fd.honeycomb.infra.bgp.BgpWritersModule",
                "io.fd.honeycomb.northbound.bgp.extension.InetModule",
                "io.fd.honeycomb.northbound.bgp.extension.EvpnModule",
                "io.fd.honeycomb.northbound.bgp.extension.L3VpnV4Module",
                "io.fd.honeycomb.northbound.bgp.extension.L3VpnV6Module",
                "io.fd.honeycomb.northbound.bgp.extension."
                "LabeledUnicastModule",
                "io.fd.honeycomb.northbound.bgp.extension.LinkstateModule"
            ]
        }

        ssh = SSH()
        ssh.connect(node)

        if feature in disabled_features.keys():
            # for every module, uncomment by replacing the entire line
            for item in disabled_features[feature]:
                find = replace = "{0}".format(item)
                if disable:
                    replace = "// {0}".format(find)

                argument = '"/{0}/c\\ {1}"'.format(find, replace)
                path = "{0}/modules/*module-config"\
                    .format(Const.REMOTE_HC_DIR)
                command = "sed -i {0} {1}".format(argument, path)

                (ret_code, _, stderr) = ssh.exec_command_sudo(command)
                if ret_code != 0:
                    raise HoneycombError("Failed to modify configuration on "
                                         "node {0}, {1}".format(node, stderr))
        else:
            raise HoneycombError("Unrecognized feature {0}.".format(feature))
コード例 #6
0
    def restart_honeycomb_and_vpp_on_duts(*nodes):
        """Restart the Honeycomb service on specified DUT nodes.

        Use the keyword "Check Honeycomb Startup State" to check when Honeycomb
        is fully restarted.
        :param nodes: List of nodes to restart Honeycomb on.
        :type nodes: list
        :raises HoneycombError: If Honeycomb failed to restart.
        """
        logger.console("\nRestarting Honeycomb service ...")

        cmd = "sudo service honeycomb restart "
        errors = []

        for node in nodes:
            if node['type'] == NodeType.DUT:
                ssh = SSH()
                ssh.connect(node)
                (ret_code, _, _) = ssh.exec_command_sudo(cmd)
                if int(ret_code) != 0:
                    errors.append(node['host'])
                try:
                    DUTSetup.setup_dut(node)
                except Exception as err:
                    logger.debug(err)
                    errors.append(node['host'])
                    continue
                logger.info("Restart of Honeycomb and VPP on node {0} is "
                            "in progress ...".format(node['host']))
        if errors:
            raise HoneycombError('Node(s) {0} failed to restart Honeycomb'
                                 ' and/or VPP.'.format(errors))
コード例 #7
0
ファイル: HcPersistence.py プロジェクト: ondrej-fabry/csit
    def clear_persisted_honeycomb_config(*nodes):
        """Remove configuration data persisted from last Honeycomb session.
        Default configuration will be used instead.

        :param nodes: List of DUTs to execute on.
        :type nodes: list
        :raises HoneycombError: If persisted configuration could not be removed.
        """
        cmd = "rm -rf {}/*".format(Const.REMOTE_HC_PERSIST)
        for node in nodes:
            if node['type'] == NodeType.DUT:
                ssh = SSH()
                ssh.connect(node)
                (ret_code, _, stderr) = ssh.exec_command_sudo(cmd)
                if ret_code != 0:
                    if "No such file or directory" not in stderr:
                        raise HoneycombError(
                            'Could not clear persisted '
                            'configuration on node {0}, {1}'.format(
                                node['host'], stderr))
                    else:
                        logger.info("Persistence data was not present on node"
                                    " {0}".format(node['host']))
                else:
                    logger.info("Persistence files removed on node {0}".format(
                        node['host']))
コード例 #8
0
    def stop_odl_client(node, path):
        """Stop ODL client service on the specified node.

        :param node: Node to start ODL client on.
        :param path: Path to ODL client.
        :type node: dict
        :type path: str
        :raises HoneycombError: If ODL client fails to stop.
        """

        ssh = SSH()
        ssh.connect(node)

        cmd = "{0}/*karaf*/bin/stop".format(path)

        ssh = SSH()
        ssh.connect(node)
        ret_code, _, _ = ssh.exec_command_sudo(cmd)
        if int(ret_code) != 0:
            logger.debug("ODL Client refused to shut down.")
            cmd = "pkill -f 'karaf'"
            (ret_code, _, _) = ssh.exec_command_sudo(cmd)
            if int(ret_code) != 0:
                raise HoneycombError('Node {0} failed to stop ODL.'.format(
                    node['host']))

        logger.info("ODL client service stopped.")
コード例 #9
0
    def copy_odl_client(node, odl_name, src_path, dst_path):
        """Copy ODL Client from source path to destination path.

        :param node: Honeycomb node.
        :param odl_name: Name of ODL client version to use.
        :param src_path: Source Path where to find ODl client.
        :param dst_path: Destination path.
        :type node: dict
        :type odl_name: str
        :type src_path: str
        :type dst_path: str
        :raises HoneycombError: If the operation fails.
        """

        ssh = SSH()
        ssh.connect(node)

        cmd = "sudo rm -rf {dst}/*karaf_{odl_name} && " \
              "cp -r {src}/*karaf_{odl_name}* {dst}".format(
                  src=src_path, odl_name=odl_name, dst=dst_path)

        ret_code, _, _ = ssh.exec_command_sudo(cmd, timeout=180)
        if int(ret_code) != 0:
            raise HoneycombError(
                "Failed to copy ODL client on node {0}".format(node["host"]))
コード例 #10
0
    def start_honeycomb_on_duts(*nodes):
        """Start Honeycomb on specified DUT nodes.

        This keyword starts the Honeycomb service on specified DUTs.
        The keyword just starts the Honeycomb and does not check its startup
        state. Use the keyword "Check Honeycomb Startup State" to check if the
        Honeycomb is up and running.
        Honeycomb must be installed in "/opt" directory, otherwise the start
        will fail.
        :param nodes: List of nodes to start Honeycomb on.
        :type nodes: list
        :raises HoneycombError: If Honeycomb fails to start.
        """

        HoneycombSetup.print_environment(nodes)

        cmd = "sudo service honeycomb start"

        for node in nodes:
            if node['type'] == NodeType.DUT:
                logger.console(
                    "\n(re)Starting Honeycomb service on node {0}".format(
                        node["host"]))
                ssh = SSH()
                ssh.connect(node)
                (ret_code, _, _) = ssh.exec_command_sudo(cmd)
                if int(ret_code) != 0:
                    raise HoneycombError(
                        'Node {0} failed to start Honeycomb.'.format(
                            node['host']))
                else:
                    logger.info(
                        "Starting the Honeycomb service on node {0} is "
                        "in progress ...".format(node['host']))
コード例 #11
0
    def stop_honeycomb_on_duts(*nodes):
        """Stop the Honeycomb service on specified DUT nodes.

        This keyword stops the Honeycomb service on specified nodes. It just
        stops the Honeycomb and does not check its shutdown state. Use the
        keyword "Check Honeycomb Shutdown State" to check if Honeycomb has
        stopped.
        :param nodes: List of nodes to stop Honeycomb on.
        :type nodes: list
        :raises HoneycombError: If Honeycomb failed to stop.
        """

        cmd = "sudo service honeycomb stop"
        errors = []

        for node in nodes:
            if node['type'] == NodeType.DUT:
                logger.console(
                    "\nShutting down Honeycomb service on node {0}".format(
                        node["host"]))
                ssh = SSH()
                ssh.connect(node)
                (ret_code, _, _) = ssh.exec_command_sudo(cmd)
                if int(ret_code) != 0:
                    errors.append(node['host'])
                else:
                    logger.info(
                        "Stopping the Honeycomb service on node {0} is "
                        "in progress ...".format(node['host']))
        if errors:
            raise HoneycombError(
                'Node(s) {0} failed to stop Honeycomb.'.format(errors))
コード例 #12
0
    def copy_java_libraries(node):
        """Copy Java libraries installed by vpp-api-java package to honeycomb
        lib folder.

        This is a (temporary?) workaround for jvpp version mismatches.

        :param node: Honeycomb node
        :type node: dict
        """

        ssh = SSH()
        ssh.connect(node)
        (_, stdout,
         _) = ssh.exec_command_sudo("ls /usr/share/java | grep ^jvpp-*")

        files = stdout.split("\n")[:-1]
        for item in files:
            # example filenames:
            # jvpp-registry-17.04.jar
            # jvpp-core-17.04.jar

            parts = item.split("-")
            version = "{0}-SNAPSHOT".format(parts[2][:5])
            artifact_id = "{0}-{1}".format(parts[0], parts[1])

            directory = "{0}/lib/io/fd/vpp/{1}/{2}".format(
                Const.REMOTE_HC_DIR, artifact_id, version)
            cmd = "sudo mkdir -p {0}; " \
                  "sudo cp /usr/share/java/{1} {0}/{2}-{3}.jar".format(
                      directory, item, artifact_id, version)

            (ret_code, _, stderr) = ssh.exec_command(cmd)
            if ret_code != 0:
                raise HoneycombError("Failed to copy JVPP libraries on "
                                     "node {0}, {1}".format(node, stderr))
コード例 #13
0
    def install_odl_features(node, path, *features):
        """Install required features on a running ODL client.

        :param node: Honeycomb node.
        :param path: Path to ODL client on node.
        :param features: Optional, list of additional features to install.
        :type node: dict
        :type path: str
        :type features: list
        """

        ssh = SSH()
        ssh.connect(node)

        cmd = "{path}/*karaf*/bin/client -u karaf feature:install " \
              "odl-restconf-all " \
              "odl-netconf-connector-all " \
              "odl-netconf-topology".format(path=path)
        for feature in features:
            cmd += " {0}".format(feature)

        ret_code, _, _ = ssh.exec_command_sudo(cmd, timeout=250)

        if int(ret_code) != 0:
            raise HoneycombError("Feature install did not succeed.")
コード例 #14
0
    def configure_restconf_binding_address(node):
        """Configure Honeycomb to accept restconf requests from all IP
        addresses. IP version is determined by node data.

         :param node: Information about a DUT node.
         :type node: dict
         :raises HoneycombError: If the configuration could not be changed.
         """

        find = "restconf-binding-address"
        try:
            IPv6Address(unicode(node["host"]))
            # if management IP of the node is in IPv6 format
            replace = '\\"restconf-binding-address\\": \\"0::0\\",'
        except (AttributeError, AddressValueError):
            replace = '\\"restconf-binding-address\\": \\"0.0.0.0\\",'

        argument = '"/{0}/c\\ {1}"'.format(find, replace)
        path = "{0}/config/restconf.json".format(Const.REMOTE_HC_DIR)
        command = "sed -i {0} {1}".format(argument, path)

        ssh = SSH()
        ssh.connect(node)
        (ret_code, _, stderr) = ssh.exec_command_sudo(command)
        if ret_code != 0:
            raise HoneycombError("Failed to modify configuration on "
                                 "node {0}, {1}".format(node, stderr))
コード例 #15
0
    def restart_honeycomb_on_dut(node):
        """Restart Honeycomb on specified DUT nodes.

        This keyword restarts the Honeycomb service on specified DUTs. Use the
        keyword "Check Honeycomb Startup State" to check if the Honeycomb is up
        and running.

        :param node: Node to restart Honeycomb on.
        :type node: dict
        :raises HoneycombError: If Honeycomb fails to start.
        """

        logger.console("\n(re)Starting Honeycomb service on node {0}".format(
            node["host"]))

        cmd = "sudo service honeycomb restart"

        ssh = SSH()
        ssh.connect(node)
        (ret_code, _, _) = ssh.exec_command_sudo(cmd)
        if int(ret_code) != 0:
            raise HoneycombError(
                'Node {0} failed to restart Honeycomb.'.format(node['host']))
        else:
            logger.info(
                "Honeycomb service restart is in progress on node {0}".format(
                    node['host']))
コード例 #16
0
ファイル: HoneycombSetup.py プロジェクト: krickwix/csit
    def mount_honeycomb_on_odl(node):
        """Tell ODL client to mount Honeycomb instance over netconf.

        :param node: Honeycomb node.
        :type node: dict
        :raises HoneycombError: When the response is not code 200: OK.
        """

        path = HcUtil.read_path_from_url_file(
            "odl_client/odl_netconf_connector")

        url_file = "{0}/{1}".format(Const.RESOURCES_TPL_HC,
                                    "odl_client/mount_honeycomb.xml")

        with open(url_file) as template:
            data = template.read()

        status_code, _ = HTTPRequest.post(
            node,
            path,
            headers={"Content-Type": "application/xml"},
            payload=data,
            timeout=10,
            enable_logging=False)

        if status_code == HTTPCodes.OK:
            logger.info("ODL mount point configured successfully.")
        elif status_code == HTTPCodes.CONFLICT:
            logger.info("ODL mount point was already configured.")
        else:
            raise HoneycombError('Mount point configuration not successful')
コード例 #17
0
    def setup_odl_client(node, path):
        """Start ODL client on the specified node.

        Karaf should be located in the provided path, and VPP and Honeycomb
        should already be running, otherwise the start will fail.
        :param node: Node to start ODL client on.
        :param path: Path to ODL client on node.
        :type node: dict
        :type path: str
        :raises HoneycombError: If Honeycomb fails to start.
        """

        logger.console("\nStarting ODL client ...")
        ssh = SSH()
        ssh.connect(node)

        cmd = "{path}/*karaf*/bin/start clean".format(path=path)
        ret_code, _, _ = ssh.exec_command_sudo(cmd)

        if int(ret_code) != 0:
            raise HoneycombError('Node {0} failed to start ODL.'.format(
                node['host']))
        else:
            logger.info("Starting the ODL client on node {0} is "
                        "in progress ...".format(node['host']))
コード例 #18
0
ファイル: HoneycombSetup.py プロジェクト: ondrej-fabry/csit
    def check_honeycomb_startup_state(node,
                                      timeout=360,
                                      retries=20,
                                      interval=15):
        """Repeatedly check the status of Honeycomb startup until it is fully
        started or until timeout or max retries is reached.

        :param node: Honeycomb node.
        :param timeout: Timeout value in seconds.
        :param retries: Max number of retries.
        :param interval: Interval between checks, in seconds.
        :type node: dict
        :type timeout: int
        :type retries: int
        :type interval: int
        :raises HoneycombError: If the Honeycomb process IP cannot be found,
            or if timeout or number of retries is exceeded.
        """

        ssh = SSH()
        ssh.connect(node)

        count = 0
        start = time()
        while time() - start < timeout and count < retries:
            count += 1

            try:
                status_code_version, _ = HcUtil.get_honeycomb_data(
                    node, "oper_vpp_version")
                status_code_if_cfg, _ = HcUtil.get_honeycomb_data(
                    node, "config_vpp_interfaces")
                status_code_if_oper, _ = HcUtil.get_honeycomb_data(
                    node, "oper_vpp_interfaces")
            except HTTPRequestError:
                sleep(interval)
                continue
            if status_code_if_cfg == HTTPCodes.OK\
                    and status_code_if_cfg == HTTPCodes.OK\
                    and status_code_if_oper == HTTPCodes.OK:
                logger.info("Check successful, Honeycomb is up and running.")
                break
            else:
                logger.debug(
                    "Attempt ${count} failed on Restconf check. Status codes:\n"
                    "Version: {version}\n"
                    "Interface config: {if_cfg}\n"
                    "Interface operational: {if_oper}".format(
                        count=count,
                        version=status_code_version,
                        if_cfg=status_code_if_cfg,
                        if_oper=status_code_if_oper))
                sleep(interval)
                continue
        else:
            _, vpp_status, _ = ssh.exec_command("sudo service vpp status")
            raise HoneycombError(
                "Timeout or max retries exceeded. Status of VPP:\n"
                "{vpp_status}".format(vpp_status=vpp_status))
コード例 #19
0
ファイル: Performance.py プロジェクト: ondrej-fabry/csit
    def run_traffic_script_on_dut(node,
                                  script,
                                  cores,
                                  reserved=2,
                                  *args,
                                  **kwargs):
        """Copy traffic script over to the specified node and execute with
        the provided arguments.

        :param node: Node in topology.
        :param script: Name of the script to execute.
        :param cores: Number of processor cores to use.
        :param reserved: Number of cores reserved for other tasks. Default is 2,
            one for system tasks and one for VPP main thread.
        :param args: Sequential arguments for the script.
        :param kwargs: Named arguments for the script.
        :type node: dict
        :type script: str
        :type cores: int
        :type reserved: int
        :type args: list
        :type kwargs: dict
        """

        path = "resources/traffic_scripts/honeycomb/{0}".format(script)

        # Assemble arguments for traffic script
        arguments = ""
        for arg in args:
            arguments += "{0} ".format(arg)

        for key, value in kwargs.items():
            arguments += "--{0} {1} ".format(key, value)

        ssh = SSH()
        ssh.connect(node)
        ssh.scp(path, "/tmp")

        # Use alternate scheduler, Ubuntu's default can't load-balance
        # over isolcpus
        scheduler = "chrt -f 99"
        core_afi = "taskset -c {first}-{last}".format(first=reserved,
                                                      last=cores - 1)

        cmd = "{scheduler} {affinity} python /tmp/{script} {args}".format(
            scheduler=scheduler,
            affinity=core_afi,
            script=script,
            args=arguments)

        ret_code, stdout, _ = ssh.exec_command_sudo(cmd, timeout=600)

        ssh.exec_command("sudo pkill python ; rm /tmp/{0}".format(script))
        if ret_code != 0:
            raise HoneycombError("Traffic script failed to execute.")
        for line in stdout.splitlines():
            if "Avg. requests" in line:
                return line
コード例 #20
0
ファイル: HoneycombSetup.py プロジェクト: krickwix/csit
    def check_honeycomb_shutdown_state(*nodes):
        """Check state of Honeycomb service during shutdown on specified nodes.

        Honeycomb nodes reply with connection refused or the following status
        codes depending on shutdown progress: codes 200, 404.

        :param nodes: List of DUT nodes stopping Honeycomb.
        :type nodes: list
        :return: True if all GETs fail to connect.
        :rtype bool
        """
        cmd = "ps -ef | grep -v grep | grep honeycomb"
        for node in nodes:
            if node['type'] == NodeType.DUT:
                try:
                    status_code, _ = HTTPRequest.get(node,
                                                     '/index.html',
                                                     enable_logging=False)
                    if status_code == HTTPCodes.OK:
                        raise HoneycombError('Honeycomb on node {0} is still '
                                             'running.'.format(node['host']),
                                             enable_logging=False)
                    elif status_code == HTTPCodes.NOT_FOUND:
                        raise HoneycombError(
                            'Honeycomb on node {0} is shutting'
                            ' down.'.format(node['host']),
                            enable_logging=False)
                    else:
                        raise HoneycombError(
                            'Unexpected return code: {0}.'.format(status_code))
                except HTTPRequestError:
                    logger.debug('Connection refused, checking the process '
                                 'state ...')
                    ssh = SSH()
                    ssh.connect(node)
                    (ret_code, _, _) = ssh.exec_command_sudo(cmd)
                    if ret_code == 0:
                        raise HoneycombError('Honeycomb on node {0} is still '
                                             'running.'.format(node['host']),
                                             enable_logging=False)
                    else:
                        logger.info("Honeycomb on node {0} has stopped".format(
                            node['host']))
        return True
コード例 #21
0
    def get_response(self, size=4096, time_out=10, err="Unspecified Error."):
        """Iteratively read data from the receive buffer and catenate together
        until message ends with the message delimiter, or
        until timeout is reached.

        :param size: Maximum number of bytes to read in one iteration.
        :param time_out: Timeout value for getting the complete response.
        :param err: Error message to provide when timeout is reached.
        :type size:int
        :type time_out:int
        :type err:str
        :returns: Content of response.
        :rtype: str
        :raises HoneycombError: If the read process times out.
        """

        reply = ''

        try:
            with timeout(time_out, exception=RuntimeError):
                while not reply.endswith(self.delimiter) or \
                        self.channel.recv_ready():
                    try:
                        chunk = self.channel.recv(size)
                        if not chunk:
                            break
                        reply += chunk
                        if self.channel.exit_status_ready():
                            logger.debug('Channel exit status ready.')
                            break
                    except socket.timeout:
                        raise HoneycombError("Socket timeout.",
                                             enable_logging=False)

        except RuntimeError:
            raise HoneycombError(err + " Content of buffer: {0}".format(reply),
                                 enable_logging=False)

        logger.trace(reply)
        return reply.replace(self.delimiter, "")
コード例 #22
0
ファイル: Netconf.py プロジェクト: ondrej-fabry/csit
    def create_session(self, node, hello, time_out=10):
        """Create an SSH session, connect to Honeycomb on the specified node,
        open a communication channel to the Netconf subsystem and exchange hello
        messages.

        :param node: Honeycomb node.
        :param hello: Hello message and capability list to be sent to Honeycomb.
        :param time_out: Timeout value for the connection in seconds.
        :type node: dict
        :type hello: str
        :type time_out: int
        """

        start = time()
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        client.connect(node['host'],
                       username=node['honeycomb']['user'],
                       password=node['honeycomb']['passwd'],
                       pkey=None,
                       port=node['honeycomb']['netconf_port'],
                       timeout=time_out)

        logger.trace('Connect took {0} seconds'.format(time() - start))
        logger.debug('New ssh: {0}'.format(client))
        logger.debug('Connect peer: {0}'.
                     format(client.get_transport().getpeername()))
        logger.debug(client)

        channel = client.get_transport().open_session()
        channel.settimeout(time_out)
        channel.set_combine_stderr(True)
        channel.get_pty()
        channel.invoke_subsystem("netconf")
        logger.debug(channel)

        self.client = client
        self.channel = channel

        # read OpenDaylight's hello message and capability list
        self.get_response(
            size=131072,
            time_out=time_out,
            err="Timeout on getting hello message."
        )

        self.channel.send(hello)
        if not self.channel.active:
            raise HoneycombError("Channel closed on capabilities exchange.")
コード例 #23
0
    def configure_odl_client(node, odl_name):
        """Start ODL client on the specified node.

        Karaf should be located in /mnt/common, and VPP and Honeycomb should
        already be running, otherwise the start will fail.
        :param node: Node to start ODL client on.
        :param odl_name: Name of ODL client version to use.
        :type node: dict
        :type odl_name: str
        :raises HoneycombError: If Honeycomb fails to start.
        """

        logger.debug("Copying ODL Client to home dir.")

        ssh = SSH()
        ssh.connect(node)

        cmd = "cp -r /mnt/common/*karaf_{name}* ~/karaf".format(name=odl_name)

        (ret_code, _, _) = ssh.exec_command_sudo(cmd)
        if int(ret_code) != 0:
            raise HoneycombError(
                "Failed to copy ODL client on node {0}".format(node["host"]))

        logger.console("\nStarting ODL client ...")

        cmd = "~/*karaf*/bin/start"

        ssh = SSH()
        ssh.connect(node)
        (ret_code, _, _) = ssh.exec_command_sudo(cmd)
        if int(ret_code) != 0:
            raise HoneycombError('Node {0} failed to start ODL.'.format(
                node['host']))
        else:
            logger.info("Starting the ODL client on node {0} is "
                        "in progress ...".format(node['host']))
コード例 #24
0
ファイル: Notifications.py プロジェクト: preym17/csit
    def add_notification_listener(self, subscription):
        """Open a new channel on the SSH session, connect to Netconf subsystem
        and subscribe to receive Honeycomb notifications.

        :param subscription: RPC for subscription to notifications.
        :type subscription: str
        :raises HoneycombError: If subscription to notifications fails.
        """

        logger.debug(subscription)
        self.send(subscription)

        reply = self.get_response(
            err="Timeout on notifications subscription."
        )

        if "<ok/>" not in reply:
            raise HoneycombError("Notifications subscription failed with"
                                 " message: {0}".format(reply))

        logger.debug("Notifications subscription successful.")
コード例 #25
0
    def configure_log_level(node, level):
        """Set Honeycomb logging to the specified level.

        :param node: Honeycomb node.
        :param level: Log level (INFO, DEBUG, TRACE).
        :type node: dict
        :type level: str
        """

        find = 'logger name=\\"io.fd\\"'
        replace = '<logger name=\\"io.fd\\" level=\\"{0}\\"/>'.format(level)

        argument = '"/{0}/c\\ {1}"'.format(find, replace)
        path = "{0}/config/logback.xml".format(Const.REMOTE_HC_DIR)
        command = "sed -i {0} {1}".format(argument, path)

        ssh = SSH()
        ssh.connect(node)
        (ret_code, _, stderr) = ssh.exec_command_sudo(command)
        if ret_code != 0:
            raise HoneycombError("Failed to modify configuration on "
                                 "node {0}, {1}".format(node, stderr))
コード例 #26
0
ファイル: Performance.py プロジェクト: ondrej-fabry/csit
    def configure_netconf_threads(node, threads):
        """Set Honeycomb's Netconf thread count in configuration.

        :param node: Honeycomb node.
        :param threads: Number of threads.
        :type node: dict
        :type threads: int
        :raises HoneycombError: If the operation fails.
        """

        find = "netconf-netty-threads"
        replace = '\\"netconf-netty-threads\\": {0},'.format(threads)

        argument = '"/{0}/c\\ {1}"'.format(find, replace)
        path = "{0}/config/netconf.json".format(Const.REMOTE_HC_DIR)
        command = "sed -i {0} {1}".format(argument, path)

        ssh = SSH()
        ssh.connect(node)
        (ret_code, _, stderr) = ssh.exec_command_sudo(command)
        if ret_code != 0:
            raise HoneycombError("Failed to modify configuration on "
                                 "node {0}, {1}".format(node, stderr))
コード例 #27
0
    def configure_jvpp_timeout(node, timeout=10):
        """Configure timeout value for Java API commands Honeycomb sends to VPP.

         :param node: Information about a DUT node.
         :param timeout: Timeout value in seconds.
         :type node: dict
         :type timeout: int
         :raises HoneycombError: If the configuration could not be changed.
         """

        find = "jvpp-request-timeout"
        replace = '\\"jvpp-request-timeout\\": {0}'.format(timeout)

        argument = '"/{0}/c\\ {1}"'.format(find, replace)
        path = "{0}/config/jvpp.json".format(Const.REMOTE_HC_DIR)
        command = "sed -i {0} {1}".format(argument, path)

        ssh = SSH()
        ssh.connect(node)
        (ret_code, _, stderr) = ssh.exec_command_sudo(command)
        if ret_code != 0:
            raise HoneycombError("Failed to modify configuration on "
                                 "node {0}, {1}".format(node, stderr))
コード例 #28
0
ファイル: HcPersistence.py プロジェクト: ondrej-fabry/csit
    def configure_persistence(node, state):
        """Enable or disable Honeycomb configuration data persistence.

        :param node: Honeycomb node.
        :param state: Enable or Disable.
        :type node: dict
        :type state: str
        :raises ValueError: If the state argument is incorrect.
        :raises HoneycombError: If the operation fails.
        """

        state = state.lower()
        if state == "enable":
            state = "true"
        elif state == "disable":
            state = "false"
        else:
            raise ValueError(
                "Unexpected value of state argument:"
                " {0} provided. Must be enable or disable.".format(state))

        for setting in ("persist-config", "persist-context"):
            # find the setting, replace entire line with 'setting: state'
            find = '\\"{setting}\\":'.format(setting=setting)
            replace = '\\"{setting}\\": \\"{state}\\",'.format(setting=setting,
                                                               state=state)

            argument = '"/{0}/c\\ {1}"'.format(find, replace)
            path = "{0}/config/honeycomb.json".format(Const.REMOTE_HC_DIR)
            command = "sed -i {0} {1}".format(argument, path)

            ssh = SSH()
            ssh.connect(node)
            (ret_code, _, stderr) = ssh.exec_command_sudo(command)
            if ret_code != 0:
                raise HoneycombError("Failed to modify configuration on "
                                     "node {0}, {1}".format(node, stderr))
コード例 #29
0
ファイル: HcPersistence.py プロジェクト: ondrej-fabry/csit
    def modify_persistence_files(node, find, replace):
        """Searches contents of persistence file data.json for the provided
         string, and replaces all occurrences with another string.

        :param node: Honeycomb node.
        :param find: Text to find in file.
        :param replace: String to replace anything found with.
        :type node: dict
        :type find: string
        :type replace: string
        :raises HoneycombError: If persistent configuration couldn't be
            modified.
        """

        argument = "\"s/{0}/{1}/g\"".format(find, replace)
        path = "{0}/config/data.json".format(Const.REMOTE_HC_PERSIST)
        command = "sed -i {0} {1}".format(argument, path)

        ssh = SSH()
        ssh.connect(node)
        (ret_code, _, stderr) = ssh.exec_command_sudo(command)
        if ret_code != 0:
            raise HoneycombError("Failed to modify persistence file on node"
                                 " {0}, {1}".format(node, stderr))
コード例 #30
0
    def check_honeycomb_shutdown_state(node):
        """Check state of Honeycomb service during shutdown on specified nodes.

        Honeycomb nodes reply with connection refused or the following status
        codes depending on shutdown progress: codes 200, 404.

        :param node: List of DUT nodes stopping Honeycomb.
        :type node: dict
        :return: True if all GETs fail to connect.
        :rtype bool
        """
        cmd = "pgrep honeycomb"

        ssh = SSH()
        ssh.connect(node)
        (ret_code, _, _) = ssh.exec_command_sudo(cmd)
        if ret_code == 0:
            raise HoneycombError('Honeycomb on node {0} is still '
                                 'running.'.format(node['host']),
                                 enable_logging=False)
        else:
            logger.info("Honeycomb on node {0} has stopped".format(
                node['host']))
        return True