コード例 #1
0
ファイル: config.py プロジェクト: dchirikov/pcs
def config_show(argv):
    print("Cluster Name: %s" % utils.getClusterName())
    status.nodes_status(["config"])
    print()
    config_show_cib()
    if (
        utils.hasCorosyncConf()
        and
        (
            utils.is_rhel6()
            or
            (not utils.usefile and "--corosync_conf" not in utils.pcs_options)
        )
    ):
        # with corosync 1 and cman, uid gid is part of cluster.conf file
        # with corosync 2, uid gid is in a separate directory
        cluster.cluster_uidgid([], True)
    if (
        "--corosync_conf" in utils.pcs_options
        or
        (not utils.is_rhel6() and utils.hasCorosyncConf())
    ):
        print()
        print("Quorum:")
        try:
            config = lib_quorum.get_config(utils.get_lib_env())
            print("\n".join(indent(quorum.quorum_config_to_str(config))))
        except LibraryError as e:
            utils.process_library_reports(e.args)
コード例 #2
0
ファイル: config.py プロジェクト: ldming/pcs
def config_show(lib, argv, modifiers):
    """
    Options:
      * -f - CIB file, when getting cluster name on remote node (corosync.conf
        doesn't exist)
      * --corosync_conf - corosync.conf file
    """
    modifiers.ensure_only_supported("-f", "--corosync_conf")
    if argv:
        raise CmdLineInputError()
    print("Cluster Name: %s" % utils.getClusterName())
    status.nodes_status(lib, ["config"], modifiers.get_subset("-f"))
    print()
    print("\n".join(_config_show_cib_lines(lib)))
    if (utils.hasCorosyncConf() and not modifiers.is_specified("-f")
            and not modifiers.is_specified("--corosync_conf")):
        cluster.cluster_uidgid(lib, [],
                               modifiers.get_subset(),
                               silent_list=True)
    if modifiers.is_specified("--corosync_conf") or utils.hasCorosyncConf():
        print()
        print("Quorum:")
        try:
            config = lib_quorum.get_config(utils.get_lib_env())
            print("\n".join(indent(quorum.quorum_config_to_str(config))))
        except LibraryError as e:
            process_library_reports(e.args)
コード例 #3
0
ファイル: config.py プロジェクト: rriifftt/pcs
def config_show(argv):
    print("Cluster Name: %s" % utils.getClusterName())
    status.nodes_status(["config"])
    print()
    config_show_cib()
    if (
        utils.hasCorosyncConf()
        and
        (
            utils.is_rhel6()
            or
            (not utils.usefile and "--corosync_conf" not in utils.pcs_options)
        )
    ):
        # with corosync 1 and cman, uid gid is part of cluster.conf file
        # with corosync 2, uid gid is in a separate directory
        cluster.cluster_uidgid([], True)
    if (
        "--corosync_conf" in utils.pcs_options
        or
        (not utils.is_rhel6() and utils.hasCorosyncConf())
    ):
        print()
        print("Quorum:")
        try:
            config = lib_quorum.get_config(utils.get_lib_env())
            print("\n".join(indent(quorum.quorum_config_to_str(config))))
        except LibraryError as e:
            utils.process_library_reports(e.args)
コード例 #4
0
ファイル: config.py プロジェクト: norbertoaquino/pcs
def config_show(argv):
    print("Cluster Name: %s" % utils.getClusterName())
    status.nodes_status(["config"])
    print()
    config_show_cib()
    cluster.cluster_uidgid([], True)
    if "--corosync_conf" in utils.pcs_options or not utils.is_rhel6():
        print()
        print("Quorum:")
        try:
            config = lib_quorum.get_config(utils.get_lib_env())
            print("\n".join(indent(quorum.quorum_config_to_str(config))))
        except LibraryError as e:
            utils.process_library_reports(e.args)
コード例 #5
0
ファイル: cluster.py プロジェクト: junaruga/pcs
def node_add_outside_cluster(lib, argv, modifiers):
    #pylint: disable=unreachable
    raise CmdLineInputError("not implemented")  # TODO
    if len(argv) != 2:
        raise CmdLineInputError(
            "Usage: pcs cluster node add-outside <node[,node-altaddr]> <cluster node>"
        )

    if len(modifiers["watchdog"]) > 1:
        raise CmdLineInputError("Multiple watchdogs defined")

    node_ring0, node_ring1 = utils.parse_multiring_node(argv[0])
    cluster_node = argv[1]
    data = [
        ("new_nodename", node_ring0),
    ]

    if node_ring1:
        data.append(("new_ring1addr", node_ring1))
    if modifiers["watchdog"]:
        data.append(("watchdog", modifiers["watchdog"][0]))
    if modifiers["device"]:
        # way to send data in array
        data += [("devices[]", device) for device in modifiers["device"]]

    communicator = utils.get_lib_env().node_communicator()
    try:
        communicator.call_host(
            cluster_node,
            "remote/add_node_all",
            communicator.format_data_dict(data),
        )
    except NodeCommandUnsuccessfulException as e:
        print(e.reason)
    except NodeCommunicationException as e:
        process_library_reports(
            [node_communicator_exception_to_report_item(e)])
コード例 #6
0
ファイル: config.py プロジェクト: ClusterLabs/pcs
def config_show(lib, argv, modifiers):
    """
    Options:
      * -f - CIB file, when getting cluster name on remote node (corosync.conf
        doesn't exist)
      * --corosync_conf - corosync.conf file
    """
    modifiers.ensure_only_supported("-f", "--corosync_conf")
    if argv:
        raise CmdLineInputError()
    print("Cluster Name: %s" % utils.getClusterName())
    status.nodes_status(lib, ["config"], modifiers.get_subset("-f"))
    print()
    print("\n".join(_config_show_cib_lines(lib)))
    if (
        utils.hasCorosyncConf()
        and
        not modifiers.is_specified("-f")
        and
        not modifiers.is_specified("--corosync_conf")
    ):
        cluster.cluster_uidgid(
            lib, [], modifiers.get_subset(), silent_list=True
        )
    if (
        modifiers.is_specified("--corosync_conf")
        or
        utils.hasCorosyncConf()
    ):
        print()
        print("Quorum:")
        try:
            config = lib_quorum.get_config(utils.get_lib_env())
            print("\n".join(indent(quorum.quorum_config_to_str(config))))
        except LibraryError as e:
            utils.process_library_reports(e.args)
コード例 #7
0
logger.addHandler(logger_handler)

global_target = RequestTarget(
    "TestServer",
    dest_list=[
        Destination("httpbin.org2", 433),
        Destination("httpbin.org", 443),
    ]
)

pprint.pprint(global_target)

def get_request(timeout):
    return Request(global_target, RequestData("delay/{0}".format(timeout)))

lib_env = utils.get_lib_env()
# utils.pcs_options["--debug"] = True
request_list = [get_request((i + 1) * 2) for i in range(6)]
factory = lib_env.get_node_communicator_factory()
factory._request_timeout = 10
communicator = factory.get_multiring_communicator()
# communicator.add_requests([get_request(10)])
# response = list(communicator.start_loop())[0]
# pprint.pprint(response.to_report_item())
communicator.add_requests(request_list)
for response in communicator.start_loop():
    # print(80 * "-")
    # print(response.request.url)
    # print(response.data)
    # print(80 * "-")
    if response.request == request_list[2]:
コード例 #8
0
def location_add(lib, argv, modifiers):
    """
    Options:
      * --force - allow unknown options, allow constraint for any resource type
      * -f - CIB file
    """
    del lib
    modifiers.ensure_only_supported("--force", "-f")
    if len(argv) < 4:
        raise CmdLineInputError()

    constraint_id = argv.pop(0)
    rsc_type, rsc_value = parse_args.parse_typed_arg(
        argv.pop(0), [RESOURCE_TYPE_RESOURCE, RESOURCE_TYPE_REGEXP],
        RESOURCE_TYPE_RESOURCE)
    node = argv.pop(0)
    score = argv.pop(0)
    options = []
    # For now we only allow setting resource-discovery
    if argv:
        for arg in argv:
            if '=' in arg:
                options.append(arg.split('=', 1))
            else:
                raise CmdLineInputError(f"bad option '{arg}'")
            if (options[-1][0] != "resource-discovery"
                    and not modifiers.get("--force")):
                utils.err("bad option '%s', use --force to override" %
                          options[-1][0])

    id_valid, id_error = utils.validate_xml_id(constraint_id, 'constraint id')
    if not id_valid:
        utils.err(id_error)

    if not utils.is_score(score):
        utils.err("invalid score '%s', use integer or INFINITY or -INFINITY" %
                  score)

    required_version = None
    if [x for x in options if x[0] == "resource-discovery"]:
        required_version = 2, 2, 0
    if rsc_type == RESOURCE_TYPE_REGEXP:
        required_version = 2, 6, 0

    if required_version:
        dom = utils.cluster_upgrade_to_version(required_version)
    else:
        dom = utils.get_cib_dom()

    if rsc_type == RESOURCE_TYPE_RESOURCE:
        rsc_valid, rsc_error, dummy_correct_id = (
            utils.validate_constraint_resource(dom, rsc_value))
        if not rsc_valid:
            utils.err(rsc_error)

    # Verify that specified node exists in the cluster
    if not (modifiers.is_specified("-f") or modifiers.get("--force")):
        lib_env = utils.get_lib_env()
        existing_nodes = get_existing_nodes_names(
            corosync_conf=lib_env.get_corosync_conf(),
            cib=lib_env.get_cib(),
        )
        if node not in existing_nodes:
            raise error(f"Node '{node}' does not seem to be in the cluster"
                        ", use --force to override")
    else:
        warn(LOCATION_NODE_VALIDATION_SKIP_MSG)

    # Verify current constraint doesn't already exist
    # If it does we replace it with the new constraint
    dummy_dom, constraintsElement = getCurrentConstraints(dom)
    elementsToRemove = []
    # If the id matches, or the rsc & node match, then we replace/remove
    for rsc_loc in constraintsElement.getElementsByTagName('rsc_location'):
        # pylint: disable=too-many-boolean-expressions
        if (rsc_loc.getAttribute("id") == constraint_id
                or (rsc_loc.getAttribute("node") == node and
                    ((RESOURCE_TYPE_RESOURCE == rsc_type
                      and rsc_loc.getAttribute("rsc") == rsc_value) or
                     (RESOURCE_TYPE_REGEXP == rsc_type
                      and rsc_loc.getAttribute("rsc-pattern") == rsc_value)))):
            elementsToRemove.append(rsc_loc)
    for etr in elementsToRemove:
        constraintsElement.removeChild(etr)

    element = dom.createElement("rsc_location")
    element.setAttribute("id", constraint_id)
    if rsc_type == RESOURCE_TYPE_RESOURCE:
        element.setAttribute("rsc", rsc_value)
    elif rsc_type == RESOURCE_TYPE_REGEXP:
        element.setAttribute("rsc-pattern", rsc_value)
    element.setAttribute("node", node)
    element.setAttribute("score", score)
    for option in options:
        element.setAttribute(option[0], option[1])
    constraintsElement.appendChild(element)

    utils.replace_cib_configuration(dom)
コード例 #9
0
ファイル: curl_test.py プロジェクト: tomjelinek/pcs
logger.addHandler(logger_handler)

global_target = RequestTarget(
    "TestServer",
    dest_list=[
        Destination("httpbin.org2", 433),
        Destination("httpbin.org", 443),
    ]
)

pprint.pprint(global_target)

def get_request(timeout):
    return Request(global_target, RequestData("delay/{0}".format(timeout)))

lib_env = utils.get_lib_env()
# utils.pcs_options["--debug"] = True
request_list = [get_request((i + 1) * 2) for i in range(6)]
factory = lib_env.get_node_communicator_factory()
factory._request_timeout = 10
communicator = factory.get_multiring_communicator()
# communicator.add_requests([get_request(10)])
# response = list(communicator.start_loop())[0]
# pprint.pprint(response.to_report_item())
communicator.add_requests(request_list)
for response in communicator.start_loop():
    # print(80 * "-")
    # print(response.request.url)
    # print(response.data)
    # print(80 * "-")
    if response.request == request_list[2]:
コード例 #10
0
ファイル: constraint.py プロジェクト: miladalipour99/pcs
def location_prefer(lib, argv, modifiers):
    """
    Options:
      * --force - allow unknown options, allow constraint for any resource type
      * -f - CIB file
    """
    modifiers.ensure_only_supported("--force", "-f")
    rsc = argv.pop(0)
    prefer_option = argv.pop(0)

    dummy_rsc_type, rsc_value = parse_args.parse_typed_arg(
        rsc, [RESOURCE_TYPE_RESOURCE, RESOURCE_TYPE_REGEXP],
        RESOURCE_TYPE_RESOURCE)

    if prefer_option == "prefers":
        prefer = True
    elif prefer_option == "avoids":
        prefer = False
    else:
        raise CmdLineInputError()

    skip_node_check = False
    if modifiers.is_specified("-f") or modifiers.get("--force"):
        skip_node_check = True
        warn(LOCATION_NODE_VALIDATION_SKIP_MSG)
    else:
        lib_env = utils.get_lib_env()
        existing_nodes, report_list = get_existing_nodes_names(
            corosync_conf=lib_env.get_corosync_conf(),
            cib=lib_env.get_cib(),
        )
        if report_list:
            process_library_reports(report_list)

    report_list = []
    parameters_list = []
    for nodeconf in argv:
        nodeconf_a = nodeconf.split("=", 1)
        node = nodeconf_a[0]
        if not skip_node_check:
            report_list += _verify_node_name(node, existing_nodes)
        if len(nodeconf_a) == 1:
            if prefer:
                score = "INFINITY"
            else:
                score = "-INFINITY"
        else:
            score = nodeconf_a[1]
            _verify_score(score)
            if not prefer:
                if score[0] == "-":
                    score = score[1:]
                else:
                    score = "-" + score

        parameters_list.append([
            sanitize_id(f"location-{rsc_value}-{node}-{score}"), rsc, node,
            score
        ])

    if report_list:
        process_library_reports(report_list)

    modifiers = modifiers.get_subset("--force", "-f")

    for parameters in parameters_list:
        location_add(lib,
                     parameters,
                     modifiers,
                     skip_score_and_node_check=True)
コード例 #11
0
ファイル: cluster.py プロジェクト: junaruga/pcs
def cluster_destroy(argv):
    if argv:
        raise CmdLineInputError()
    if "--all" in utils.pcs_options:
        # destroy remote and guest nodes
        cib = None
        lib_env = utils.get_lib_env()
        try:
            cib = lib_env.get_cib()
        except LibraryError as e:
            warn("Unable to load CIB to get guest and remote nodes from it, "
                 "those nodes will not be deconfigured.")
        if cib is not None:
            try:
                all_remote_nodes = get_existing_nodes_names(cib=cib)
                if len(all_remote_nodes) > 0:
                    _destroy_pcmk_remote_env(lib_env,
                                             all_remote_nodes,
                                             skip_offline_nodes=True,
                                             allow_fails=True)
            except LibraryError as e:
                utils.process_library_reports(e.args)

        # destroy full-stack nodes
        destroy_cluster(utils.get_corosync_conf_facade().get_nodes_names())
    else:
        print("Shutting down pacemaker/corosync services...")
        for service in ["pacemaker", "corosync-qdevice", "corosync"]:
            # Returns an error if a service is not running. It is safe to
            # ignore it since we want it not to be running anyways.
            utils.stop_service(service)
        print("Killing any remaining services...")
        kill_local_cluster_services()
        try:
            utils.disableServices()
        except:
            # previously errors were suppressed in here, let's keep it that way
            # for now
            pass
        try:
            disable_service(utils.cmd_runner(), lib_sbd.get_sbd_service_name())
        except:
            # it's not a big deal if sbd disable fails
            pass

        print("Removing all cluster configuration files...")
        dummy_output, dummy_retval = utils.run([
            "rm",
            "-f",
            settings.corosync_conf_file,
            settings.corosync_authkey_file,
            settings.pacemaker_authkey_file,
        ])
        state_files = [
            "cib.xml*", "cib-*", "core.*", "hostcache", "cts.*", "pe*.bz2",
            "cib.*"
        ]
        for name in state_files:
            dummy_output, dummy_retval = utils.run([
                "find", "/var/lib/pacemaker", "-name", name, "-exec", "rm",
                "-f", "{}", ";"
            ])
        try:
            qdevice_net.client_destroy()
        except:
            # errors from deleting other files are suppressed as well
            # we do not want to fail if qdevice was not set up
            pass
コード例 #12
0
ファイル: cluster.py プロジェクト: junaruga/pcs
def cluster_auth_cmd(lib, argv, modifiers):
    if argv:
        raise CmdLineInputError()
    lib_env = utils.get_lib_env()
    target_factory = lib_env.get_node_target_factory()
    cluster_node_list = lib_env.get_corosync_conf().get_nodes()
    cluster_node_names = []
    missing_name = False
    for node in cluster_node_list:
        if node.name:
            cluster_node_names.append(node.name)
        else:
            missing_name = True
    if missing_name:
        print(
            "Warning: Skipping nodes which do not have their name defined in "
            "corosync.conf, use the 'pcs host auth' command to authenticate "
            "them")
    target_list = []
    not_authorized_node_name_list = []
    for node_name in cluster_node_names:
        try:
            target_list.append(target_factory.get_target(node_name))
        except HostNotFound:
            print("{}: Not authorized".format(node_name))
            not_authorized_node_name_list.append(node_name)
    com_cmd = CheckAuth(lib_env.report_processor)
    com_cmd.set_targets(target_list)
    not_authorized_node_name_list.extend(
        run_and_raise(lib_env.get_node_communicator(), com_cmd))
    if not_authorized_node_name_list:
        print("Nodes to authorize: {}".format(
            ", ".join(not_authorized_node_name_list)))
        username, password = utils.get_user_and_pass()
        not_auth_node_list = []
        for node_name in not_authorized_node_name_list:
            for node in cluster_node_list:
                if node.name == node_name:
                    if node.addrs_plain:
                        not_auth_node_list.append(node)
                    else:
                        print(
                            f"{node.name}: No addresses defined in "
                            "corosync.conf, use the 'pcs host auth' command to "
                            "authenticate the node")
        nodes_to_auth_data = {
            node.name: dict(
                username=username,
                password=password,
                dest_list=[
                    dict(
                        addr=node.addrs_plain[0],
                        port=settings.pcsd_default_port,
                    )
                ],
            )
            for node in not_auth_node_list
        }
        utils.auth_hosts(nodes_to_auth_data)
    else:
        print("Sending cluster config files to the nodes...")
        msgs = send_local_configs(cluster_node_names, force=True)
        for msg in msgs:
            print("Warning: {0}".format(msg))