Example #1
0
def config_show_cib():
    lib = utils.get_library_wrapper()
    modifiers = utils.get_modifiers()

    print("Resources:")
    utils.pcs_options["--all"] = 1
    utils.pcs_options["--full"] = 1
    resource.resource_show([])

    print()
    print("Stonith Devices:")
    resource.resource_show([], True)
    print("Fencing Levels:")
    levels = stonith.stonith_level_config_to_str(
        lib.fencing_topology.get_config())
    if levels:
        print("\n".join(indent(levels, 2)))

    print()
    constraint.location_show([])
    order_command.show(lib, [], modifiers)
    colocation_command.show(lib, [], modifiers)
    ticket_command.show(lib, [], modifiers)

    print()
    alert.print_alert_config(lib, [], modifiers)

    print()
    del utils.pcs_options["--all"]
    print("Resources Defaults:")
    resource.show_defaults("rsc_defaults", indent=" ")
    print("Operations Defaults:")
    resource.show_defaults("op_defaults", indent=" ")
    print()
    prop.list_property([])
Example #2
0
def stonith_cmd(argv):
    if len(argv) < 1:
        sub_cmd, argv_next = "show", []
    else:
        sub_cmd, argv_next = argv[0], argv[1:]

    lib = utils.get_library_wrapper()
    modifiers = utils.get_modifiers()

    try:
        if sub_cmd == "help":
            usage.stonith([" ".join(argv_next)] if argv_next else [])
        elif sub_cmd == "list":
            stonith_list_available(lib, argv_next, modifiers)
        elif sub_cmd == "describe":
            stonith_list_options(lib, argv_next, modifiers)
        elif sub_cmd == "create":
            stonith_create(lib, argv_next, modifiers)
        elif sub_cmd == "update":
            if len(argv_next) > 1:
                stn_id = argv_next.pop(0)
                resource.resource_update(stn_id, argv_next)
            else:
                raise CmdLineInputError()
        elif sub_cmd == "delete":
            if len(argv_next) == 1:
                stn_id = argv_next.pop(0)
                resource.resource_remove(stn_id)
            else:
                raise CmdLineInputError()
        elif sub_cmd == "show":
            resource.resource_show(argv_next, True)
            levels = stonith_level_config_to_str(
                lib.fencing_topology.get_config())
            if levels:
                print("\n".join(indent(levels, 1)))
        elif sub_cmd == "level":
            stonith_level_cmd(lib, argv_next, modifiers)
        elif sub_cmd == "fence":
            stonith_fence(argv_next)
        elif sub_cmd == "cleanup":
            resource.resource_cleanup(argv_next)
        elif sub_cmd == "refresh":
            resource.resource_refresh(argv_next)
        elif sub_cmd == "confirm":
            stonith_confirm(argv_next)
        elif sub_cmd == "get_fence_agent_info":
            get_fence_agent_info(argv_next)
        elif sub_cmd == "sbd":
            sbd_cmd(lib, argv_next, modifiers)
        elif sub_cmd == "enable":
            resource.resource_enable_cmd(lib, argv_next, modifiers)
        elif sub_cmd == "disable":
            resource.resource_disable_cmd(lib, argv_next, modifiers)
        else:
            raise CmdLineInputError()
    except LibraryError as e:
        utils.process_library_reports(e.args)
    except CmdLineInputError as e:
        utils.exit_on_cmdline_input_errror(e, "stonith", sub_cmd)
Example #3
0
def config_show_cib():
    print("Resources:")
    utils.pcs_options["--all"] = 1
    utils.pcs_options["--full"] = 1
    resource.resource_show([])
    print()
    print("Stonith Devices:")
    resource.resource_show([], True)
    print("Fencing Levels:")
    stonith.stonith_level_show()
    print()

    lib = utils.get_library_wrapper()
    constraint.location_show([])
    modificators = utils.get_modificators()
    order_command.show(lib, [], modificators)
    colocation_command.show(lib, [], modificators)
    ticket_command.show(lib, [], modificators)

    print()
    alert.print_alert_config(lib, [], modificators)

    print()
    del utils.pcs_options["--all"]
    print("Resources Defaults:")
    resource.show_defaults("rsc_defaults", indent=" ")
    print("Operations Defaults:")
    resource.show_defaults("op_defaults", indent=" ")
    print()
    prop.list_property([])
Example #4
0
def status_cmd(argv):
    if len(argv) == 0:
        full_status()
        sys.exit(0)

    sub_cmd = argv.pop(0)
    if (sub_cmd == "help"):
        usage.status(argv)
    elif (sub_cmd == "resources"):
        resource.resource_show(argv)
    elif (sub_cmd == "groups"):
        resource.resource_group_list(argv)
    elif (sub_cmd == "cluster"):
        cluster_status(argv)
    elif (sub_cmd == "nodes"):
        nodes_status(argv)
    elif (sub_cmd == "pcsd"):
        cluster_pcsd_status(argv)
    elif (sub_cmd == "xml"):
        xml_status()
    elif (sub_cmd == "corosync"):
        corosync_status()
    elif sub_cmd == "qdevice":
        try:
            qdevice_status_cmd(
                utils.get_library_wrapper(),
                argv,
                utils.get_modificators()
            )
        except LibraryError as e:
            utils.process_library_reports(e.args)
        except CmdLineInputError as e:
            utils.exit_on_cmdline_input_errror(e, "status", sub_cmd)
    elif sub_cmd == "quorum":
        try:
            quorum_status_cmd(
                utils.get_library_wrapper(),
                argv,
                utils.get_modificators()
            )
        except LibraryError as e:
            utils.process_library_reports(e.args)
        except CmdLineInputError as e:
            utils.exit_on_cmdline_input_errror(e, "status", sub_cmd)
    else:
        usage.status()
        sys.exit(1)
Example #5
0
def stonith_cmd(argv):
    if len(argv) < 1:
        sub_cmd, argv_next = "show", []
    else:
        sub_cmd, argv_next = argv[0], argv[1:]

    lib = utils.get_library_wrapper()
    modifiers = utils.get_modificators()

    try:
        if sub_cmd == "help":
            usage.stonith(argv)
        elif sub_cmd == "list":
            stonith_list_available(lib, argv_next, modifiers)
        elif sub_cmd == "describe":
            stonith_list_options(lib, argv_next, modifiers)
        elif sub_cmd == "create":
            stonith_create(lib, argv_next, modifiers)
        elif sub_cmd == "update":
            if len(argv_next) > 1:
                stn_id = argv_next.pop(0)
                resource.resource_update(stn_id, argv_next)
            else:
                raise CmdLineInputError()
        elif sub_cmd == "delete":
            if len(argv_next) == 1:
                stn_id = argv_next.pop(0)
                resource.resource_remove(stn_id)
            else:
                raise CmdLineInputError()
        elif sub_cmd == "show":
            resource.resource_show(argv_next, True)
            levels = stonith_level_config_to_str(
                lib.fencing_topology.get_config()
            )
            if levels:
                print("\n".join(indent(levels, 1)))
        elif sub_cmd == "level":
            stonith_level_cmd(lib, argv_next, modifiers)
        elif sub_cmd == "fence":
            stonith_fence(argv_next)
        elif sub_cmd == "cleanup":
            resource.resource_cleanup(argv_next)
        elif sub_cmd == "confirm":
            stonith_confirm(argv_next)
        elif sub_cmd == "get_fence_agent_info":
            get_fence_agent_info(argv_next)
        elif sub_cmd == "sbd":
            sbd_cmd(lib, argv_next, modifiers)
        elif sub_cmd == "enable":
            resource.resource_enable(argv_next)
        elif sub_cmd == "disable":
            resource.resource_disable(argv_next)
        else:
            raise CmdLineInputError()
    except LibraryError as e:
        utils.process_library_reports(e.args)
    except CmdLineInputError as e:
        utils.exit_on_cmdline_input_errror(e, "stonith", sub_cmd)
Example #6
0
def stonith_cmd(argv):
    lib = utils.get_library_wrapper()
    modifiers = utils.get_modificators()
    if len(argv) == 0:
        argv = ["show"]

    sub_cmd = argv.pop(0)
    try:
        if (sub_cmd == "help"):
            usage.stonith(argv)
        elif (sub_cmd == "list"):
            stonith_list_available(argv)
        elif (sub_cmd == "describe"):
            if len(argv) == 1:
                stonith_list_options(argv[0])
            else:
                raise CmdLineInputError()
        elif (sub_cmd == "create"):
            stonith_create(argv)
        elif (sub_cmd == "update"):
            if len(argv) > 1:
                stn_id = argv.pop(0)
                resource.resource_update(stn_id,argv)
            else:
                raise CmdLineInputError()
        elif (sub_cmd == "delete"):
            if len(argv) == 1:
                stn_id = argv.pop(0)
                resource.resource_remove(stn_id)
            else:
                raise CmdLineInputError()
        elif (sub_cmd == "show"):
            resource.resource_show(argv, True)
            stonith_level([])
        elif (sub_cmd == "level"):
            stonith_level(argv)
        elif (sub_cmd == "fence"):
            stonith_fence(argv)
        elif (sub_cmd == "cleanup"):
            resource.resource_cleanup(argv)
        elif (sub_cmd == "confirm"):
            stonith_confirm(argv)
        elif (sub_cmd == "get_fence_agent_info"):
            get_fence_agent_info(argv)
        elif (sub_cmd == "sbd"):
            sbd_cmd(lib, argv, modifiers)
        else:
            raise CmdLineInputError()
    except LibraryError as e:
        utils.process_library_reports(e.args)
    except CmdLineInputError as e:
        utils.exit_on_cmdline_input_errror(e, "stonith", sub_cmd)
Example #7
0
def stonith_cmd(argv):
    if len(argv) < 1:
        sub_cmd, argv_next = "show", []
    else:
        sub_cmd, argv_next = argv[0], argv[1:]

    lib = utils.get_library_wrapper()
    modifiers = utils.get_modificators()

    try:
        if sub_cmd == "help":
            usage.stonith(argv)
        elif sub_cmd == "list":
            stonith_list_available(lib, argv_next, modifiers)
        elif sub_cmd == "describe":
            stonith_list_options(lib, argv_next, modifiers)
        elif sub_cmd == "create":
            stonith_create(argv_next)
        elif sub_cmd == "update":
            if len(argv_next) > 1:
                stn_id = argv_next.pop(0)
                resource.resource_update(stn_id, argv_next)
            else:
                raise CmdLineInputError()
        elif sub_cmd == "delete":
            if len(argv_next) == 1:
                stn_id = argv_next.pop(0)
                resource.resource_remove(stn_id)
            else:
                raise CmdLineInputError()
        elif sub_cmd == "show":
            resource.resource_show(argv_next, True)
            stonith_level([])
        elif sub_cmd == "level":
            stonith_level(argv_next)
        elif sub_cmd == "fence":
            stonith_fence(argv_next)
        elif sub_cmd == "cleanup":
            resource.resource_cleanup(argv_next)
        elif sub_cmd == "confirm":
            stonith_confirm(argv_next)
        elif sub_cmd == "get_fence_agent_info":
            get_fence_agent_info(argv_next)
        elif sub_cmd == "sbd":
            sbd_cmd(lib, argv_next, modifiers)
        else:
            raise CmdLineInputError()
    except LibraryError as e:
        utils.process_library_reports(e.args)
    except CmdLineInputError as e:
        utils.exit_on_cmdline_input_errror(e, "stonith", sub_cmd)
Example #8
0
def remove_constraints_containing(
    resource_id, output=False, constraints_element=None, passed_dom=None
):
    """
    Commandline options:
      * -f - CIB file, effective only if passed_dom is None
    """
    lib = utils.get_library_wrapper()
    modifiers = utils.get_input_modifiers()
    constraints, set_constraints = find_constraints_containing(
        resource_id,
        passed_dom
    )
    for c in constraints:
        if output:
            print("Removing Constraint - " + c)
        if constraints_element is not None:
            constraint_rm(
                lib, [c], modifiers, True, constraints_element,
                passed_dom=passed_dom
            )
        else:
            constraint_rm(lib, [c], modifiers, passed_dom=passed_dom)

    if set_constraints:
        (dom, constraintsElement) = getCurrentConstraints(passed_dom)
        for c in constraintsElement.getElementsByTagName("resource_ref")[:]:
            # If resource id is in a set, remove it from the set, if the set
            # is empty, then we remove the set, if the parent of the set
            # is empty then we remove it
            if c.getAttribute("id") == resource_id:
                pn = c.parentNode
                pn.removeChild(c)
                if output:
                    print(
                        "Removing %s from set %s"
                        % (resource_id, pn.getAttribute("id"))
                    )
                if pn.getElementsByTagName("resource_ref").length == 0:
                    print("Removing set %s" % pn.getAttribute("id"))
                    pn2 = pn.parentNode
                    pn2.removeChild(pn)
                    if pn2.getElementsByTagName("resource_set").length == 0:
                        pn2.parentNode.removeChild(pn2)
                        print("Removing constraint %s" % pn2.getAttribute("id"))
        if passed_dom:
            return dom
        utils.replace_cib_configuration(dom)
    return None
Example #9
0
def cluster_verify(argv):
    if len(argv) > 1:
        usage.cluster("verify")
        raise SystemExit(1)

    if argv:
        filename = argv[0]
        if not utils.usefile:
            #We must operate on given cib everywhere.
            utils.usefile = True
            utils.filename = filename
        elif os.path.abspath(filename) == os.path.abspath(utils.filename):
            warn("File '{0}' specified twice".format(
                os.path.abspath(filename)))
        else:
            raise error(
                "Ambiguous cib filename specification: '{0}' vs  -f '{1}'".
                format(filename, utils.filename))

    lib = utils.get_library_wrapper()
    try:
        lib.cluster.verify(verbose="-V" in utils.pcs_options)
    except LibraryError as e:
        utils.process_library_reports(e.args)
Example #10
0
def main(argv=None):
    if completion.has_applicable_environment(os.environ):
        print(
            completion.make_suggestions(
                os.environ, usage.generate_completion_tree_from_usage()))
        sys.exit()

    argv = argv if argv else sys.argv[1:]
    utils.subprocess_setup()
    global filename, usefile
    orig_argv = argv[:]
    utils.pcs_options = {}
    modified_argv = []
    real_argv = []
    try:
        # we change --cloneopt to "clone" for backwards compatibility
        new_argv = []
        for arg in argv:
            if arg == "--cloneopt" or arg == "--clone":
                new_argv.append("clone")
            elif arg.startswith("--cloneopt="):
                new_argv.append("clone")
                new_argv.append(arg.split('=', 1)[1])
            else:
                new_argv.append(arg)
        argv = new_argv

        # we want to support optional arguments for --wait, so if an argument
        # is specified with --wait (ie. --wait=30) then we use them
        waitsecs = None
        new_argv = []
        for arg in argv:
            if arg.startswith("--wait="):
                tempsecs = arg.replace("--wait=", "")
                if len(tempsecs) > 0:
                    waitsecs = tempsecs
                    arg = "--wait"
            new_argv.append(arg)
        argv = new_argv

        # h = help, f = file,
        # p = password (cluster auth), u = user (cluster auth),
        # V = verbose (cluster verify)
        pcs_short_options = "hf:p:u:V"
        pcs_long_options = [
            "debug",
            "version",
            "help",
            "fullhelp",
            "force",
            "skip-offline",
            "autocorrect",
            "interactive",
            "autodelete",
            "all",
            "full",
            "groups",
            "local",
            "wait",
            "config",
            "start",
            "enable",
            "disabled",
            "off",
            "pacemaker",
            "corosync",
            "no-default-ops",
            "defaults",
            "nodesc",
            "clone",
            "master",
            "name=",
            "group=",
            "node=",
            "from=",
            "to=",
            "after=",
            "before=",
            "transport=",
            "rrpmode=",
            "ipv6",
            "addr0=",
            "bcast0=",
            "mcast0=",
            "mcastport0=",
            "ttl0=",
            "broadcast0",
            "addr1=",
            "bcast1=",
            "mcast1=",
            "mcastport1=",
            "ttl1=",
            "broadcast1",
            "wait_for_all=",
            "auto_tie_breaker=",
            "last_man_standing=",
            "last_man_standing_window=",
            "token=",
            "token_coefficient=",
            "consensus=",
            "join=",
            "miss_count_const=",
            "fail_recv_const=",
            "corosync_conf=",
            "cluster_conf=",
            "booth-conf=",
            "booth-key=",
            "remote",
            "watchdog=",
            #in pcs status - do not display resorce status on inactive node
            "hide-inactive",
        ]
        # pull out negative number arguments and add them back after getopt
        prev_arg = ""
        for arg in argv:
            if len(arg) > 0 and arg[0] == "-":
                if arg[1:].isdigit() or arg[1:].startswith("INFINITY"):
                    real_argv.append(arg)
                else:
                    modified_argv.append(arg)
            else:
                # If previous argument required an argument, then this arg
                # should not be added back in
                if not prev_arg or (
                        not (prev_arg[0] == "-"
                             and prev_arg[1:] in pcs_short_options)
                        and not (prev_arg[0:2] == "--" and
                                 (prev_arg[2:] + "=") in pcs_long_options)):
                    real_argv.append(arg)
                modified_argv.append(arg)
            prev_arg = arg

        pcs_options, argv = getopt.gnu_getopt(modified_argv, pcs_short_options,
                                              pcs_long_options)
    except getopt.GetoptError as err:
        print(err)
        usage.main()
        sys.exit(1)
    argv = real_argv
    for o, a in pcs_options:
        if not o in utils.pcs_options:
            if o == "--watchdog":
                a = [a]
            utils.pcs_options[o] = a
        else:
            # If any options are a list then they've been entered twice which isn't valid
            if o != "--watchdog":
                utils.err("%s can only be used once" % o)
            else:
                utils.pcs_options[o].append(a)

        if o == "-h" or o == "--help":
            if len(argv) == 0:
                usage.main()
                sys.exit()
            else:
                argv = [argv[0], "help"] + argv[1:]
        elif o == "-f":
            usefile = True
            filename = a
            utils.usefile = usefile
            utils.filename = filename
        elif o == "--corosync_conf":
            settings.corosync_conf_file = a
        elif o == "--cluster_conf":
            settings.cluster_conf_file = a
        elif o == "--version":
            print(settings.pcs_version)
            sys.exit()
        elif o == "--fullhelp":
            usage.full_usage()
            sys.exit()
        elif o == "--wait":
            utils.pcs_options[o] = waitsecs

    if len(argv) == 0:
        usage.main()
        sys.exit(1)

    # create a dummy logger
    # we do not have a log file for cli (yet), but library requires a logger
    logger = logging.getLogger("old_cli")
    logger.propagate = 0
    logger.handlers = []

    command = argv.pop(0)
    if (command == "-h" or command == "help"):
        usage.main()
        return
    cmd_map = {
        "resource":
        resource.resource_cmd,
        "cluster":
        cluster.cluster_cmd,
        "stonith":
        stonith.stonith_cmd,
        "property":
        prop.property_cmd,
        "constraint":
        constraint.constraint_cmd,
        "acl":
        lambda argv: acl.acl_cmd(utils.get_library_wrapper(), argv,
                                 utils.get_modificators()),
        "status":
        status.status_cmd,
        "config":
        config.config_cmd,
        "pcsd":
        pcsd.pcsd_cmd,
        "node":
        node.node_cmd,
        "quorum":
        lambda argv: quorum.quorum_cmd(utils.get_library_wrapper(), argv,
                                       utils.get_modificators()),
        "qdevice":
        lambda argv: qdevice.qdevice_cmd(utils.get_library_wrapper(), argv,
                                         utils.get_modificators()),
        "alert":
        lambda args: alert.alert_cmd(utils.get_library_wrapper(), args,
                                     utils.get_modificators()),
        "booth":
        lambda argv: booth.booth_cmd(utils.get_library_wrapper(), argv,
                                     utils.get_modificators()),
    }
    if command not in cmd_map:
        usage.main()
        sys.exit(1)
    # root can run everything directly, also help can be displayed,
    # working on a local file also do not need to run under root
    if (os.getuid() == 0) or (argv and argv[0] == "help") or usefile:
        cmd_map[command](argv)
        return
    # specific commands need to be run under root account, pass them to pcsd
    # don't forget to allow each command in pcsd.rb in "post /run_pcs do"
    root_command_list = [
        ['cluster', 'auth', '...'],
        ['cluster', 'corosync', '...'],
        ['cluster', 'destroy', '...'],
        ['cluster', 'disable', '...'],
        ['cluster', 'enable', '...'],
        ['cluster', 'node', '...'],
        ['cluster', 'pcsd-status', '...'],
        ['cluster', 'setup', '...'],
        ['cluster', 'start', '...'],
        ['cluster', 'stop', '...'],
        ['cluster', 'sync', '...'],
        # ['config', 'restore', '...'], # handled in config.config_restore
        ['pcsd', 'sync-certificates'],
        ['status', 'nodes', 'corosync-id'],
        ['status', 'nodes', 'pacemaker-id'],
        ['status', 'pcsd', '...'],
    ]
    argv_cmd = argv[:]
    argv_cmd.insert(0, command)
    for root_cmd in root_command_list:
        if ((argv_cmd == root_cmd)
                or (root_cmd[-1] == "..."
                    and argv_cmd[:len(root_cmd) - 1] == root_cmd[:-1])):
            # handle interactivity of 'pcs cluster auth'
            if argv_cmd[0:2] == ["cluster", "auth"]:
                if "-u" not in utils.pcs_options:
                    username = utils.get_terminal_input('Username: ')
                    orig_argv.extend(["-u", username])
                if "-p" not in utils.pcs_options:
                    password = utils.get_terminal_password()
                    orig_argv.extend(["-p", password])

            # call the local pcsd
            err_msgs, exitcode, std_out, std_err = utils.call_local_pcsd(
                orig_argv, True)
            if err_msgs:
                for msg in err_msgs:
                    utils.err(msg, False)
                sys.exit(1)
            if std_out.strip():
                print(std_out)
            if std_err.strip():
                sys.stderr.write(std_err)
            sys.exit(exitcode)
            return
    cmd_map[command](argv)
Example #11
0
def main(argv=None):
    # pylint: disable=global-statement
    # pylint: disable=too-many-branches
    # pylint: disable=too-many-locals
    # pylint: disable=too-many-statements
    if completion.has_applicable_environment(os.environ):
        print(
            completion.make_suggestions(
                os.environ, usage.generate_completion_tree_from_usage()
            )
        )
        sys.exit()

    argv = argv if argv else sys.argv[1:]
    utils.subprocess_setup()
    global filename, usefile
    utils.pcs_options = {}

    # we want to support optional arguments for --wait, so if an argument
    # is specified with --wait (ie. --wait=30) then we use them
    waitsecs = None
    new_argv = []
    for arg in argv:
        if arg.startswith("--wait="):
            tempsecs = arg.replace("--wait=", "")
            if tempsecs:
                waitsecs = tempsecs
                arg = "--wait"
        new_argv.append(arg)
    argv = new_argv

    try:
        if "--" in argv:
            pcs_options, argv = getopt.gnu_getopt(
                argv, parse_args.PCS_SHORT_OPTIONS, parse_args.PCS_LONG_OPTIONS
            )
        else:
            # DEPRECATED
            # TODO remove
            # We want to support only the -- version
            (
                args_without_negative_nums,
                args_filtered_out,
            ) = parse_args.filter_out_non_option_negative_numbers(argv)
            if args_filtered_out:
                options_str = "', '".join(args_filtered_out)
                output.warn(
                    f"Using '{options_str}' without '--' is deprecated, those "
                    "parameters will be considered position independent "
                    "options in future pcs versions"
                )
            pcs_options, dummy_argv = getopt.gnu_getopt(
                args_without_negative_nums,
                parse_args.PCS_SHORT_OPTIONS,
                parse_args.PCS_LONG_OPTIONS,
            )
            argv = parse_args.filter_out_options(argv)
    except getopt.GetoptError as err:
        usage.main()
        print(err)
        if err.opt in {"V", "clone", "device", "watchdog"}:
            # Print error messages which point users to the changes section in
            # pcs manpage.
            # TODO remove
            # To be removed in the next significant version.
            print(f"Hint: {errors.HINT_SYNTAX_CHANGE}")
        sys.exit(1)

    full = False
    for option, dummy_value in pcs_options:
        if option == "--full":
            full = True
            break

    for opt, val in pcs_options:
        if not opt in utils.pcs_options:
            utils.pcs_options[opt] = val
        else:
            # If any options are a list then they've been entered twice which
            # isn't valid
            utils.err("%s can only be used once" % opt)

        if opt in ("-h", "--help"):
            if not argv:
                usage.main()
                sys.exit()
            else:
                argv = [argv[0], "help"] + argv[1:]
        elif opt == "-f":
            usefile = True
            filename = val
            utils.usefile = usefile
            utils.filename = filename
        elif opt == "--corosync_conf":
            settings.corosync_conf_file = val
        elif opt == "--version":
            print(settings.pcs_version)
            if full:
                print(
                    " ".join(
                        sorted(
                            [
                                feat["id"]
                                for feat in capabilities.get_pcs_capabilities()
                            ]
                        )
                    )
                )
            sys.exit()
        elif opt == "--fullhelp":
            usage.full_usage()
            sys.exit()
        elif opt == "--wait":
            utils.pcs_options[opt] = waitsecs
        elif opt == "--request-timeout":
            request_timeout_valid = False
            try:
                timeout = int(val)
                if timeout > 0:
                    utils.pcs_options[opt] = timeout
                    request_timeout_valid = True
            except ValueError:
                pass
            if not request_timeout_valid:
                utils.err(
                    (
                        "'{0}' is not a valid --request-timeout value, use "
                        "a positive integer"
                    ).format(val)
                )

    logger = logging.getLogger("pcs")
    logger.propagate = 0
    logger.handlers = []

    if (os.getuid() != 0) and (argv and argv[0] != "help") and not usefile:
        _non_root_run(argv)
    cmd_map = {
        "resource": resource.resource_cmd,
        "cluster": cluster.cluster_cmd,
        "stonith": stonith.stonith_cmd,
        "property": prop.property_cmd,
        "constraint": constraint.constraint_cmd,
        "acl": acl.acl_cmd,
        "status": status.status_cmd,
        "config": config.config_cmd,
        "pcsd": pcsd.pcsd_cmd,
        "node": node.node_cmd,
        "quorum": quorum.quorum_cmd,
        "qdevice": qdevice.qdevice_cmd,
        "alert": alert.alert_cmd,
        "booth": booth.booth_cmd,
        "host": host.host_cmd,
        "client": client.client_cmd,
        "dr": dr.dr_cmd,
        "tag": tag.tag_cmd,
        "help": lambda lib, argv, modifiers: usage.main(),
    }
    try:
        routing.create_router(cmd_map, [])(
            utils.get_library_wrapper(), argv, utils.get_input_modifiers()
        )
    except LibraryError as e:
        process_library_reports(e.args)
    except errors.CmdLineInputError:
        if argv and argv[0] in cmd_map:
            usage.show(argv[0], [])
        else:
            usage.main()
        sys.exit(1)
Example #12
0
def main(argv=None):
    # pylint: disable=too-many-locals, too-many-branches, too-many-statements, global-statement
    if completion.has_applicable_environment(os.environ):
        print(completion.make_suggestions(
            os.environ,
            usage.generate_completion_tree_from_usage()
        ))
        sys.exit()

    argv = argv if argv else sys.argv[1:]
    utils.subprocess_setup()
    global filename, usefile
    utils.pcs_options = {}

    # we want to support optional arguments for --wait, so if an argument
    # is specified with --wait (ie. --wait=30) then we use them
    waitsecs = None
    new_argv = []
    for arg in argv:
        if arg.startswith("--wait="):
            tempsecs = arg.replace("--wait=", "")
            if tempsecs:
                waitsecs = tempsecs
                arg = "--wait"
        new_argv.append(arg)
    argv = new_argv

    try:
        pcs_options, dummy_argv = getopt.gnu_getopt(
            parse_args.filter_out_non_option_negative_numbers(argv),
            parse_args.PCS_SHORT_OPTIONS,
            parse_args.PCS_LONG_OPTIONS,
        )
    except getopt.GetoptError as err:
        print(err)
        usage.main()
        sys.exit(1)
    argv = parse_args.filter_out_options(argv)

    full = False
    for option, dummy_value in pcs_options:
        if option == "--full":
            full = True
            break

    for opt, val in pcs_options:
        if not opt in utils.pcs_options:
            utils.pcs_options[opt] = val
        else:
            # If any options are a list then they've been entered twice which
            # isn't valid
            utils.err("%s can only be used once" % opt)

        if opt in ("-h", "--help"):
            if  not argv:
                usage.main()
                sys.exit()
            else:
                argv = [argv[0], "help"] + argv[1:]
        elif opt == "-f":
            usefile = True
            filename = val
            utils.usefile = usefile
            utils.filename = filename
        elif opt == "--corosync_conf":
            settings.corosync_conf_file = val
        elif opt == "--version":
            print(settings.pcs_version)
            if full:
                print(" ".join(
                    sorted([
                        feat["id"]
                        for feat in capabilities.get_pcs_capabilities()
                    ])
                ))
            sys.exit()
        elif opt == "--fullhelp":
            usage.full_usage()
            sys.exit()
        elif opt == "--wait":
            utils.pcs_options[opt] = waitsecs
        elif opt == "--request-timeout":
            request_timeout_valid = False
            try:
                timeout = int(val)
                if timeout > 0:
                    utils.pcs_options[opt] = timeout
                    request_timeout_valid = True
            except ValueError:
                pass
            if not request_timeout_valid:
                utils.err(
                    (
                        "'{0}' is not a valid --request-timeout value, use "
                        "a positive integer"
                    ).format(val)
                )

    logger = logging.getLogger("pcs")
    logger.propagate = 0
    logger.handlers = []

    if (os.getuid() != 0) and (argv and argv[0] != "help") and not usefile:
        non_root_run(argv)
    cmd_map = {
        "resource": resource.resource_cmd,
        "cluster": cluster.cluster_cmd,
        "stonith": stonith.stonith_cmd,
        "property": prop.property_cmd,
        "constraint": constraint.constraint_cmd,
        "acl": acl.acl_cmd,
        "status": status.status_cmd,
        "config": config.config_cmd,
        "pcsd": pcsd.pcsd_cmd,
        "node": node.node_cmd,
        "quorum": quorum.quorum_cmd,
        "qdevice": qdevice.qdevice_cmd,
        "alert": alert.alert_cmd,
        "booth": booth.booth_cmd,
        "host": host.host_cmd,
        "client": client.client_cmd,
        "help": lambda lib, argv, modifiers: usage.main(),
    }
    try:
        routing.create_router(cmd_map, [])(
            utils.get_library_wrapper(), argv, utils.get_input_modifiers()
        )
    except LibraryError as e:
        utils.process_library_reports(e.args)
    except errors.CmdLineInputError:
        if argv and argv[0] in cmd_map:
            usage.show(argv[0], [])
        else:
            usage.main()
        sys.exit(1)
Example #13
0
File: app.py Project: dchirikov/pcs
def main(argv=None):
    if completion.has_applicable_environment(os.environ):
        print(completion.make_suggestions(
            os.environ,
            usage.generate_completion_tree_from_usage()
        ))
        sys.exit()

    argv = argv if argv else sys.argv[1:]
    utils.subprocess_setup()
    global filename, usefile
    orig_argv = argv[:]
    utils.pcs_options = {}
    modified_argv = []
    real_argv = []
    try:
        # we change --cloneopt to "clone" for backwards compatibility
        new_argv = []
        for arg in argv:
            if arg == "--cloneopt" or arg == "--clone":
                new_argv.append("clone")
            elif arg.startswith("--cloneopt="):
                new_argv.append("clone")
                new_argv.append(arg.split('=',1)[1])
            else:
                new_argv.append(arg)
        argv = new_argv

        # we want to support optional arguments for --wait, so if an argument
        # is specified with --wait (ie. --wait=30) then we use them
        waitsecs = None
        new_argv = []
        for arg in argv:
            if arg.startswith("--wait="):
                tempsecs = arg.replace("--wait=","")
                if len(tempsecs) > 0:
                    waitsecs = tempsecs
                    arg = "--wait"
            new_argv.append(arg)
        argv = new_argv

        # h = help, f = file,
        # p = password (cluster auth), u = user (cluster auth),
        # V = verbose (cluster verify)
        pcs_short_options = "hf:p:u:V"
        pcs_long_options = [
            "debug", "version", "help", "fullhelp",
            "force", "skip-offline", "autocorrect", "interactive", "autodelete",
            "all", "full", "groups", "local", "wait", "config",
            "start", "enable", "disabled", "off",
            "pacemaker", "corosync",
            "no-default-ops", "defaults", "nodesc",
            "clone", "master", "name=", "group=", "node=",
            "from=", "to=", "after=", "before=",
            "transport=", "rrpmode=", "ipv6",
            "addr0=", "bcast0=", "mcast0=", "mcastport0=", "ttl0=", "broadcast0",
            "addr1=", "bcast1=", "mcast1=", "mcastport1=", "ttl1=", "broadcast1",
            "wait_for_all=", "auto_tie_breaker=", "last_man_standing=",
            "last_man_standing_window=",
            "token=", "token_coefficient=", "consensus=", "join=",
            "miss_count_const=", "fail_recv_const=",
            "corosync_conf=", "cluster_conf=",
            "remote", "watchdog=",
            #in pcs status - do not display resorce status on inactive node
            "hide-inactive",
        ]
        # pull out negative number arguments and add them back after getopt
        prev_arg = ""
        for arg in argv:
            if len(arg) > 0 and arg[0] == "-":
                if arg[1:].isdigit() or arg[1:].startswith("INFINITY"):
                    real_argv.append(arg)
                else:
                    modified_argv.append(arg)
            else:
                # If previous argument required an argument, then this arg
                # should not be added back in
                if not prev_arg or (not (prev_arg[0] == "-" and prev_arg[1:] in pcs_short_options) and not (prev_arg[0:2] == "--" and (prev_arg[2:] + "=") in pcs_long_options)):
                    real_argv.append(arg)
                modified_argv.append(arg)
            prev_arg = arg

        pcs_options, argv = getopt.gnu_getopt(modified_argv, pcs_short_options, pcs_long_options)
    except getopt.GetoptError as err:
        print(err)
        usage.main()
        sys.exit(1)
    argv = real_argv
    for o, a in pcs_options:
        if not o in utils.pcs_options:
            if o == "--watchdog":
                a = [a]
            utils.pcs_options[o] = a
        else:
            # If any options are a list then they've been entered twice which isn't valid
            if o != "--watchdog":
                utils.err("%s can only be used once" % o)
            else:
                utils.pcs_options[o].append(a)

        if o == "-h" or o == "--help":
            if len(argv) == 0:
                usage.main()
                sys.exit()
            else:
                argv = [argv[0], "help" ] + argv[1:]
        elif o == "-f":
            usefile = True
            filename = a
            utils.usefile = usefile
            utils.filename = filename
        elif o == "--corosync_conf":
            settings.corosync_conf_file = a
        elif o == "--cluster_conf":
            settings.cluster_conf_file = a
        elif o == "--version":
            print(settings.pcs_version)
            sys.exit()
        elif o == "--fullhelp":
            usage.full_usage()
            sys.exit()
        elif o == "--wait":
            utils.pcs_options[o] = waitsecs

    if len(argv) == 0:
        usage.main()
        sys.exit(1)

    # create a dummy logger
    # we do not have a log file for cli (yet), but library requires a logger
    logger = logging.getLogger("old_cli")
    logger.propagate = 0
    logger.handlers = []

    command = argv.pop(0)
    if (command == "-h" or command == "help"):
        usage.main()
        return
    cmd_map = {
        "resource": resource.resource_cmd,
        "cluster": cluster.cluster_cmd,
        "stonith": stonith.stonith_cmd,
        "property": prop.property_cmd,
        "constraint": constraint.constraint_cmd,
        "acl": acl.acl_cmd,
        "status": status.status_cmd,
        "config": config.config_cmd,
        "pcsd": pcsd.pcsd_cmd,
        "node": node.node_cmd,
        "quorum": lambda argv: quorum.quorum_cmd(
            utils.get_library_wrapper(),
            argv,
            utils.get_modificators()
        ),
        "qdevice": lambda argv: qdevice.qdevice_cmd(
            utils.get_library_wrapper(),
            argv,
            utils.get_modificators()
        ),
        "alert": lambda args: alert.alert_cmd(
            utils.get_library_wrapper(),
            args,
            utils.get_modificators()
        ),
    }
    if command not in cmd_map:
        usage.main()
        sys.exit(1)
    # root can run everything directly, also help can be displayed,
    # working on a local file also do not need to run under root
    if (os.getuid() == 0) or (argv and argv[0] == "help") or usefile:
        cmd_map[command](argv)
        return
    # specific commands need to be run under root account, pass them to pcsd
    # don't forget to allow each command in pcsd.rb in "post /run_pcs do"
    root_command_list = [
        ['cluster', 'auth', '...'],
        ['cluster', 'corosync', '...'],
        ['cluster', 'destroy', '...'],
        ['cluster', 'disable', '...'],
        ['cluster', 'enable', '...'],
        ['cluster', 'node', '...'],
        ['cluster', 'pcsd-status', '...'],
        ['cluster', 'setup', '...'],
        ['cluster', 'start', '...'],
        ['cluster', 'stop', '...'],
        ['cluster', 'sync', '...'],
        # ['config', 'restore', '...'], # handled in config.config_restore
        ['pcsd', 'sync-certificates'],
        ['status', 'nodes', 'corosync-id'],
        ['status', 'nodes', 'pacemaker-id'],
        ['status', 'pcsd', '...'],
    ]
    argv_cmd = argv[:]
    argv_cmd.insert(0, command)
    for root_cmd in root_command_list:
        if (
            (argv_cmd == root_cmd)
            or
            (
                root_cmd[-1] == "..."
                and
                argv_cmd[:len(root_cmd)-1] == root_cmd[:-1]
            )
        ):
            # handle interactivity of 'pcs cluster auth'
            if argv_cmd[0:2] == ["cluster", "auth"]:
                if "-u" not in utils.pcs_options:
                    username = utils.get_terminal_input('Username: ')
                    orig_argv.extend(["-u", username])
                if "-p" not in utils.pcs_options:
                    password = utils.get_terminal_password()
                    orig_argv.extend(["-p", password])

            # call the local pcsd
            err_msgs, exitcode, std_out, std_err = utils.call_local_pcsd(
                orig_argv, True
            )
            if err_msgs:
                for msg in err_msgs:
                    utils.err(msg, False)
                sys.exit(1)
            if std_out.strip():
                print(std_out)
            if std_err.strip():
                sys.stderr.write(std_err)
            sys.exit(exitcode)
            return
    cmd_map[command](argv)
Example #14
0
def cluster_cmd(argv):
    if len(argv) == 0:
        usage.cluster()
        exit(1)

    sub_cmd = argv.pop(0)
    if (sub_cmd == "help"):
        usage.cluster([" ".join(argv)] if argv else [])
    elif (sub_cmd == "setup"):
        try:
            cluster_setup(utils.get_library_wrapper(), argv,
                          utils.get_modifiers())
        except LibraryError as e:
            process_library_reports(e.args)
        except CmdLineInputError as e:
            utils.exit_on_cmdline_input_errror(e, "cluster", sub_cmd)
    elif (sub_cmd == "sync"):
        sync_nodes(utils.get_corosync_conf_facade().get_nodes_names(),
                   utils.getCorosyncConf())
    elif (sub_cmd == "status"):
        status.cluster_status(argv)
    elif (sub_cmd == "pcsd-status"):
        status.cluster_pcsd_status(argv)
    elif (sub_cmd == "certkey"):
        cluster_certkey(argv)
    elif (sub_cmd == "auth"):
        try:
            cluster_auth_cmd(utils.get_library_wrapper(), argv,
                             utils.get_modifiers())
        except LibraryError as e:
            process_library_reports(e.args)
        except CmdLineInputError as e:
            utils.exit_on_cmdline_input_errror(e, "cluster", sub_cmd)
    elif (sub_cmd == "start"):
        if "--all" in utils.pcs_options:
            if argv:
                utils.err(ERR_NODE_LIST_AND_ALL_MUTUALLY_EXCLUSIVE)
            start_cluster_all()
        else:
            start_cluster(argv)
    elif (sub_cmd == "stop"):
        if "--all" in utils.pcs_options:
            if argv:
                utils.err(ERR_NODE_LIST_AND_ALL_MUTUALLY_EXCLUSIVE)
            stop_cluster_all()
        else:
            stop_cluster(argv)
    elif (sub_cmd == "kill"):
        kill_cluster(argv)
    elif (sub_cmd == "standby"):
        try:
            node.node_standby_cmd(utils.get_library_wrapper(), argv,
                                  utils.get_modifiers(), True)
        except LibraryError as e:
            utils.process_library_reports(e.args)
        except CmdLineInputError as e:
            utils.exit_on_cmdline_input_errror(e, "node", "standby")
    elif (sub_cmd == "unstandby"):
        try:
            node.node_standby_cmd(utils.get_library_wrapper(), argv,
                                  utils.get_modifiers(), False)
        except LibraryError as e:
            utils.process_library_reports(e.args)
        except CmdLineInputError as e:
            utils.exit_on_cmdline_input_errror(e, "node", "unstandby")
    elif (sub_cmd == "enable"):
        if "--all" in utils.pcs_options:
            if argv:
                utils.err(ERR_NODE_LIST_AND_ALL_MUTUALLY_EXCLUSIVE)
            enable_cluster_all()
        else:
            enable_cluster(argv)
    elif (sub_cmd == "disable"):
        if "--all" in utils.pcs_options:
            if argv:
                utils.err(ERR_NODE_LIST_AND_ALL_MUTUALLY_EXCLUSIVE)
            disable_cluster_all()
        else:
            disable_cluster(argv)
    elif (sub_cmd == "remote-node"):
        try:
            cluster_remote_node(argv)
        except LibraryError as e:
            utils.process_library_reports(e.args)
    elif (sub_cmd == "cib"):
        get_cib(argv)
    elif (sub_cmd == "cib-push"):
        cluster_push(argv)
    elif (sub_cmd == "cib-upgrade"):
        utils.cluster_upgrade()
    elif (sub_cmd == "edit"):
        cluster_edit(argv)
    elif (sub_cmd == "node"):
        node_command_map = {
            "add":
            node_add,
            "add-guest":
            cluster_command.node_add_guest,
            "add-outside":
            node_add_outside_cluster,
            "add-remote":
            cluster_command.node_add_remote,
            "clear":
            cluster_command.node_clear,
            "remove":
            node_remove,
            "remove-guest":
            cluster_command.node_remove_guest,
            "remove-remote":
            cluster_command.create_node_remove_remote(
                resource.resource_remove),
        }
        if argv and argv[0] in node_command_map:
            try:
                node_command_map[argv[0]](utils.get_library_wrapper(),
                                          argv[1:], utils.get_modifiers())
            except LibraryError as e:
                process_library_reports(e.args)
            except CmdLineInputError as e:
                utils.exit_on_cmdline_input_errror(e, "cluster",
                                                   "node " + argv[0])
        else:
            usage.cluster(["node"])
            sys.exit(1)
    elif (sub_cmd == "uidgid"):
        cluster_uidgid(argv)
    elif (sub_cmd == "corosync"):
        cluster_get_corosync_conf(argv)
    elif (sub_cmd == "reload"):
        cluster_reload(argv)
    elif (sub_cmd == "destroy"):
        try:
            cluster_destroy(argv)
        except CmdLineInputError as e:
            utils.exit_on_cmdline_input_errror(e, "cluster", sub_cmd)
    elif (sub_cmd == "verify"):
        cluster_verify(argv)
    elif (sub_cmd == "report"):
        cluster_report(argv)
    elif (sub_cmd == "quorum"):
        if argv and argv[0] == "unblock":
            quorum.quorum_unblock_cmd(argv[1:])
        else:
            usage.cluster()
            sys.exit(1)
    elif (sub_cmd == "remove_nodes_from_cib"):
        try:
            remove_nodes_from_cib(
                utils.get_library_wrapper(),
                argv,
                utils.get_modifiers(),
            )
        except LibraryError as e:
            process_library_reports(e.args)
        except CmdLineInputError as e:
            utils.exit_on_cmdline_input_errror(e, "cluster", sub_cmd)
    else:
        usage.cluster()
        sys.exit(1)
Example #15
0
def main(argv=None):
    if completion.has_applicable_environment(os.environ):
        print(completion.make_suggestions(
            os.environ,
            usage.generate_completion_tree_from_usage()
        ))
        sys.exit()

    argv = argv if argv else sys.argv[1:]
    utils.subprocess_setup()
    global filename, usefile
    orig_argv = argv[:]
    utils.pcs_options = {}

    argv = parse_args.upgrade_args(argv)

    # we want to support optional arguments for --wait, so if an argument
    # is specified with --wait (ie. --wait=30) then we use them
    waitsecs = None
    new_argv = []
    for arg in argv:
        if arg.startswith("--wait="):
            tempsecs = arg.replace("--wait=","")
            if len(tempsecs) > 0:
                waitsecs = tempsecs
                arg = "--wait"
        new_argv.append(arg)
    argv = new_argv

    try:
        pcs_options, dummy_argv = getopt.gnu_getopt(
            parse_args.filter_out_non_option_negative_numbers(argv),
            parse_args.PCS_SHORT_OPTIONS,
            parse_args.PCS_LONG_OPTIONS,
        )
    except getopt.GetoptError as err:
        print(err)
        usage.main()
        sys.exit(1)
    argv = parse_args.filter_out_options(argv)
    for o, a in pcs_options:
        if not o in utils.pcs_options:
            if o == "--watchdog":
                a = [a]
            utils.pcs_options[o] = a
        else:
            # If any options are a list then they've been entered twice which isn't valid
            if o != "--watchdog":
                utils.err("%s can only be used once" % o)
            else:
                utils.pcs_options[o].append(a)

        if o == "-h" or o == "--help":
            if len(argv) == 0:
                usage.main()
                sys.exit()
            else:
                argv = [argv[0], "help" ] + argv[1:]
        elif o == "-f":
            usefile = True
            filename = a
            utils.usefile = usefile
            utils.filename = filename
        elif o == "--corosync_conf":
            settings.corosync_conf_file = a
        elif o == "--cluster_conf":
            settings.cluster_conf_file = a
        elif o == "--version":
            print(settings.pcs_version)
            sys.exit()
        elif o == "--fullhelp":
            usage.full_usage()
            sys.exit()
        elif o == "--wait":
            utils.pcs_options[o] = waitsecs
        elif o == "--request-timeout":
            request_timeout_valid = False
            try:
                timeout = int(a)
                if timeout > 0:
                    utils.pcs_options[o] = timeout
                    request_timeout_valid = True
            except ValueError:
                pass
            if not request_timeout_valid:
                utils.err(
                    (
                        "'{0}' is not a valid --request-timeout value, use "
                        "a positive integer"
                    ).format(a)
                )

    if len(argv) == 0:
        usage.main()
        sys.exit(1)

    # create a dummy logger
    # we do not have a log file for cli (yet), but library requires a logger
    logger = logging.getLogger("old_cli")
    logger.propagate = 0
    logger.handlers = []

    command = argv.pop(0)
    if (command == "-h" or command == "help"):
        usage.main()
        return
    cmd_map = {
        "resource": resource.resource_cmd,
        "cluster": cluster.cluster_cmd,
        "stonith": stonith.stonith_cmd,
        "property": prop.property_cmd,
        "constraint": constraint.constraint_cmd,
        "acl": lambda argv: acl.acl_cmd(
            utils.get_library_wrapper(),
            argv,
            utils.get_modificators()
        ),
        "status": status.status_cmd,
        "config": config.config_cmd,
        "pcsd": pcsd.pcsd_cmd,
        "node": lambda argv: node.node_cmd(
            utils.get_library_wrapper(),
            argv,
            utils.get_modificators()
        ),
        "quorum": lambda argv: quorum.quorum_cmd(
            utils.get_library_wrapper(),
            argv,
            utils.get_modificators()
        ),
        "qdevice": lambda argv: qdevice.qdevice_cmd(
            utils.get_library_wrapper(),
            argv,
            utils.get_modificators()
        ),
        "alert": lambda args: alert.alert_cmd(
            utils.get_library_wrapper(),
            args,
            utils.get_modificators()
        ),
        "booth": lambda argv: booth.booth_cmd(
            utils.get_library_wrapper(),
            argv,
            utils.get_modificators()
        ),
    }
    if command not in cmd_map:
        usage.main()
        sys.exit(1)
    # root can run everything directly, also help can be displayed,
    # working on a local file also do not need to run under root
    if (os.getuid() == 0) or (argv and argv[0] == "help") or usefile:
        cmd_map[command](argv)
        return
    # specific commands need to be run under root account, pass them to pcsd
    # don't forget to allow each command in pcsd.rb in "post /run_pcs do"
    root_command_list = [
        ['cluster', 'auth', '...'],
        ['cluster', 'corosync', '...'],
        ['cluster', 'destroy', '...'],
        ['cluster', 'disable', '...'],
        ['cluster', 'enable', '...'],
        ['cluster', 'node', '...'],
        ['cluster', 'pcsd-status', '...'],
        ['cluster', 'setup', '...'],
        ['cluster', 'start', '...'],
        ['cluster', 'stop', '...'],
        ['cluster', 'sync', '...'],
        # ['config', 'restore', '...'], # handled in config.config_restore
        ['pcsd', 'sync-certificates'],
        ['status', 'nodes', 'corosync-id'],
        ['status', 'nodes', 'pacemaker-id'],
        ['status', 'pcsd', '...'],
    ]
    argv_cmd = argv[:]
    argv_cmd.insert(0, command)
    for root_cmd in root_command_list:
        if (
            (argv_cmd == root_cmd)
            or
            (
                root_cmd[-1] == "..."
                and
                argv_cmd[:len(root_cmd)-1] == root_cmd[:-1]
            )
        ):
            # handle interactivity of 'pcs cluster auth'
            if argv_cmd[0:2] == ["cluster", "auth"]:
                if "-u" not in utils.pcs_options:
                    username = utils.get_terminal_input('Username: ')
                    orig_argv.extend(["-u", username])
                if "-p" not in utils.pcs_options:
                    password = utils.get_terminal_password()
                    orig_argv.extend(["-p", password])

            # call the local pcsd
            err_msgs, exitcode, std_out, std_err = utils.call_local_pcsd(
                orig_argv, True
            )
            if err_msgs:
                for msg in err_msgs:
                    utils.err(msg, False)
                sys.exit(1)
            if std_out.strip():
                print(std_out)
            if std_err.strip():
                sys.stderr.write(std_err)
            sys.exit(exitcode)
            return
    cmd_map[command](argv)
Example #16
0
File: app.py Project: miz-take/pcs
def main(argv=None):
    if completion.has_applicable_environment(os.environ):
        print(
            completion.make_suggestions(
                os.environ, usage.generate_completion_tree_from_usage()))
        sys.exit()

    argv = argv if argv else sys.argv[1:]
    utils.subprocess_setup()
    global filename, usefile
    orig_argv = argv[:]
    utils.pcs_options = {}

    argv = parse_args.upgrade_args(argv)

    # we want to support optional arguments for --wait, so if an argument
    # is specified with --wait (ie. --wait=30) then we use them
    waitsecs = None
    new_argv = []
    for arg in argv:
        if arg.startswith("--wait="):
            tempsecs = arg.replace("--wait=", "")
            if len(tempsecs) > 0:
                waitsecs = tempsecs
                arg = "--wait"
        new_argv.append(arg)
    argv = new_argv

    try:
        pcs_options, dummy_argv = getopt.gnu_getopt(
            parse_args.filter_out_non_option_negative_numbers(argv),
            parse_args.PCS_SHORT_OPTIONS,
            parse_args.PCS_LONG_OPTIONS,
        )
    except getopt.GetoptError as err:
        print(err)
        usage.main()
        sys.exit(1)
    argv = parse_args.filter_out_options(argv)

    full = False
    for option, dummy_value in pcs_options:
        if option == "--full":
            full = True
            break

    for o, a in pcs_options:
        if not o in utils.pcs_options:
            if o in ["--watchdog", "--device"]:
                a = [a]
            utils.pcs_options[o] = a
        else:
            # If any options are a list then they've been entered twice which isn't valid
            if o not in ["--watchdog", "--device"]:
                utils.err("%s can only be used once" % o)
            else:
                utils.pcs_options[o].append(a)

        if o == "-h" or o == "--help":
            if len(argv) == 0:
                usage.main()
                sys.exit()
            else:
                argv = [argv[0], "help"] + argv[1:]
        elif o == "-f":
            usefile = True
            filename = a
            utils.usefile = usefile
            utils.filename = filename
        elif o == "--corosync_conf":
            settings.corosync_conf_file = a
        elif o == "--cluster_conf":
            settings.cluster_conf_file = a
        elif o == "--version":
            print(settings.pcs_version)
            if full:
                print(" ".join(
                    sorted([
                        feat["id"]
                        for feat in capabilities.get_pcs_capabilities()
                    ])))
            sys.exit()
        elif o == "--fullhelp":
            usage.full_usage()
            sys.exit()
        elif o == "--wait":
            utils.pcs_options[o] = waitsecs
        elif o == "--request-timeout":
            request_timeout_valid = False
            try:
                timeout = int(a)
                if timeout > 0:
                    utils.pcs_options[o] = timeout
                    request_timeout_valid = True
            except ValueError:
                pass
            if not request_timeout_valid:
                utils.err(("'{0}' is not a valid --request-timeout value, use "
                           "a positive integer").format(a))

    if len(argv) == 0:
        usage.main()
        sys.exit(1)

    # create a dummy logger
    # we do not have a log file for cli (yet), but library requires a logger
    logger = logging.getLogger("old_cli")
    logger.propagate = 0
    logger.handlers = []

    command = argv.pop(0)
    if (command == "-h" or command == "help"):
        usage.main()
        return
    cmd_map = {
        "resource":
        resource.resource_cmd,
        "cluster":
        cluster.cluster_cmd,
        "stonith":
        stonith.stonith_cmd,
        "property":
        prop.property_cmd,
        "constraint":
        constraint.constraint_cmd,
        "acl":
        lambda argv: acl.acl_cmd(utils.get_library_wrapper(), argv,
                                 utils.get_modificators()),
        "status":
        status.status_cmd,
        "config":
        config.config_cmd,
        "pcsd":
        pcsd.pcsd_cmd,
        "node":
        lambda argv: node.node_cmd(utils.get_library_wrapper(), argv,
                                   utils.get_modificators()),
        "quorum":
        lambda argv: quorum.quorum_cmd(utils.get_library_wrapper(), argv,
                                       utils.get_modificators()),
        "qdevice":
        lambda argv: qdevice.qdevice_cmd(utils.get_library_wrapper(), argv,
                                         utils.get_modificators()),
        "alert":
        lambda args: alert.alert_cmd(utils.get_library_wrapper(), args,
                                     utils.get_modificators()),
        "booth":
        lambda argv: booth.booth_cmd(utils.get_library_wrapper(), argv,
                                     utils.get_modificators()),
    }
    if command not in cmd_map:
        usage.main()
        sys.exit(1)
    # root can run everything directly, also help can be displayed,
    # working on a local file also do not need to run under root
    if (os.getuid() == 0) or (argv and argv[0] == "help") or usefile:
        cmd_map[command](argv)
        return
    # specific commands need to be run under root account, pass them to pcsd
    # don't forget to allow each command in pcsd.rb in "post /run_pcs do"
    root_command_list = [
        ['cluster', 'auth', '...'],
        ['cluster', 'corosync', '...'],
        ['cluster', 'destroy', '...'],
        ['cluster', 'disable', '...'],
        ['cluster', 'enable', '...'],
        ['cluster', 'node', '...'],
        ['cluster', 'pcsd-status', '...'],
        ['cluster', 'setup', '...'],
        ['cluster', 'start', '...'],
        ['cluster', 'stop', '...'],
        ['cluster', 'sync', '...'],
        # ['config', 'restore', '...'], # handled in config.config_restore
        ['pcsd', 'sync-certificates'],
        ['status', 'nodes', 'corosync-id'],
        ['status', 'nodes', 'pacemaker-id'],
        ['status', 'pcsd', '...'],
    ]
    argv_cmd = argv[:]
    argv_cmd.insert(0, command)
    for root_cmd in root_command_list:
        if ((argv_cmd == root_cmd)
                or (root_cmd[-1] == "..."
                    and argv_cmd[:len(root_cmd) - 1] == root_cmd[:-1])):
            # handle interactivity of 'pcs cluster auth'
            if argv_cmd[0:2] == ["cluster", "auth"]:
                if "-u" not in utils.pcs_options:
                    username = utils.get_terminal_input('Username: ')
                    orig_argv.extend(["-u", username])
                if "-p" not in utils.pcs_options:
                    password = utils.get_terminal_password()
                    orig_argv.extend(["-p", password])

            # call the local pcsd
            err_msgs, exitcode, std_out, std_err = utils.call_local_pcsd(
                orig_argv, True)
            if err_msgs:
                for msg in err_msgs:
                    utils.err(msg, False)
                sys.exit(1)
            if std_out.strip():
                print(std_out)
            if std_err.strip():
                sys.stderr.write(std_err)
            sys.exit(exitcode)
            return
    cmd_map[command](argv)
Example #17
0
def constraint_cmd(argv):
    lib = utils.get_library_wrapper()
    modificators = utils.get_modificators()
    if len(argv) == 0:
        argv = ["list"]

    sub_cmd = argv.pop(0)
    if (sub_cmd == "help"):
        usage.constraint(argv)
    elif (sub_cmd == "location"):
        if len (argv) == 0:
            sub_cmd2 = "show"
        else:
            sub_cmd2 = argv.pop(0)

        if (sub_cmd2 == "add"):
            location_add(argv)
        elif (sub_cmd2 in ["remove","delete"]):
            location_add(argv,True)
        elif (sub_cmd2 == "show"):
            location_show(argv)
        elif len(argv) >= 2:
            if argv[0] == "rule":
                location_rule([sub_cmd2] + argv)
            else:
                location_prefer([sub_cmd2] + argv)
        else:
            usage.constraint()
            sys.exit(1)
    elif (sub_cmd == "order"):
        if (len(argv) == 0):
            sub_cmd2 = "show"
        else:
            sub_cmd2 = argv.pop(0)

        if (sub_cmd2 == "set"):
            try:
                order_command.create_with_set(lib, argv, modificators)
            except CmdLineInputError as e:
                utils.exit_on_cmdline_input_errror(e, "constraint", 'order set')
            except LibraryError as e:
                utils.process_library_reports(e.args)
        elif (sub_cmd2 in ["remove","delete"]):
            order_rm(argv)
        elif (sub_cmd2 == "show"):
            order_command.show(lib, argv, modificators)
        else:
            order_start([sub_cmd2] + argv)
    elif sub_cmd == "ticket":
        usage_name = "ticket"
        try:
            command_map = {
                "set": ticket_command.create_with_set,
                "add": ticket_command.add,
                "show": ticket_command.show,
            }
            sub_command = argv[0] if argv else "show"
            if sub_command not in command_map:
                raise CmdLineInputError()
            usage_name = "ticket "+sub_command

            command_map[sub_command](lib, argv[1:], modificators)
        except LibraryError as e:
            utils.process_library_reports(e.args)
        except CmdLineInputError as e:
            utils.exit_on_cmdline_input_errror(e, "constraint", usage_name)

    elif (sub_cmd == "colocation"):
        if (len(argv) == 0):
            sub_cmd2 = "show"
        else:
            sub_cmd2 = argv.pop(0)

        if (sub_cmd2 == "add"):
            colocation_add(argv)
        elif (sub_cmd2 in ["remove","delete"]):
            colocation_rm(argv)
        elif (sub_cmd2 == "set"):
            try:

                colocation_command.create_with_set(lib, argv, modificators)
            except LibraryError as e:
                utils.process_library_reports(e.args)
            except CmdLineInputError as e:
                utils.exit_on_cmdline_input_errror(e, "constraint", "colocation set")
        elif (sub_cmd2 == "show"):
            colocation_command.show(lib, argv, modificators)
        else:
            usage.constraint()
            sys.exit(1)
    elif (sub_cmd in ["remove","delete"]):
        constraint_rm(argv)
    elif (sub_cmd == "show" or sub_cmd == "list"):
        location_show(argv)
        order_command.show(lib, argv, modificators)
        colocation_command.show(lib, argv, modificators)
        ticket_command.show(lib, argv, modificators)
    elif (sub_cmd == "ref"):
        constraint_ref(argv)
    elif (sub_cmd == "rule"):
        constraint_rule(argv)
    else:
        usage.constraint()
        sys.exit(1)
Example #18
0
def constraint_cmd(argv):
    lib = utils.get_library_wrapper()
    modificators = utils.get_modificators()

    if len(argv) == 0:
        argv = ["list"]
    sub_cmd = argv.pop(0)

    try:
        if (sub_cmd == "help"):
            usage.constraint(argv)
        elif (sub_cmd == "location"):
            if len(argv) == 0:
                sub_cmd2 = "show"
            else:
                sub_cmd2 = argv.pop(0)

            if (sub_cmd2 == "add"):
                location_add(argv)
            elif (sub_cmd2 in ["remove", "delete"]):
                location_add(argv, True)
            elif (sub_cmd2 == "show"):
                location_show(argv)
            elif len(argv) >= 2:
                if argv[0] == "rule":
                    location_rule([sub_cmd2] + argv)
                else:
                    location_prefer([sub_cmd2] + argv)
            else:
                usage.constraint()
                sys.exit(1)
        elif (sub_cmd == "order"):
            if (len(argv) == 0):
                sub_cmd2 = "show"
            else:
                sub_cmd2 = argv.pop(0)

            if (sub_cmd2 == "set"):
                try:
                    order_command.create_with_set(lib, argv, modificators)
                except CmdLineInputError as e:
                    utils.exit_on_cmdline_input_errror(e, "constraint",
                                                       'order set')
                except LibraryError as e:
                    utils.process_library_reports(e.args)
            elif (sub_cmd2 in ["remove", "delete"]):
                order_rm(argv)
            elif (sub_cmd2 == "show"):
                order_command.show(lib, argv, modificators)
            else:
                order_start([sub_cmd2] + argv)
        elif sub_cmd == "ticket":
            usage_name = "ticket"
            try:
                command_map = {
                    "set": ticket_command.create_with_set,
                    "add": ticket_command.add,
                    "remove": ticket_command.remove,
                    "show": ticket_command.show,
                }
                sub_command = argv[0] if argv else "show"
                if sub_command not in command_map:
                    raise CmdLineInputError()
                usage_name = "ticket " + sub_command

                command_map[sub_command](lib, argv[1:], modificators)
            except LibraryError as e:
                utils.process_library_reports(e.args)
            except CmdLineInputError as e:
                utils.exit_on_cmdline_input_errror(e, "constraint", usage_name)

        elif (sub_cmd == "colocation"):
            if (len(argv) == 0):
                sub_cmd2 = "show"
            else:
                sub_cmd2 = argv.pop(0)

            if (sub_cmd2 == "add"):
                colocation_add(argv)
            elif (sub_cmd2 in ["remove", "delete"]):
                colocation_rm(argv)
            elif (sub_cmd2 == "set"):
                try:

                    colocation_command.create_with_set(lib, argv, modificators)
                except LibraryError as e:
                    utils.process_library_reports(e.args)
                except CmdLineInputError as e:
                    utils.exit_on_cmdline_input_errror(e, "constraint",
                                                       "colocation set")
            elif (sub_cmd2 == "show"):
                colocation_command.show(lib, argv, modificators)
            else:
                usage.constraint()
                sys.exit(1)
        elif (sub_cmd in ["remove", "delete"]):
            constraint_rm(argv)
        elif (sub_cmd == "show" or sub_cmd == "list"):
            location_show(argv)
            order_command.show(lib, argv, modificators)
            colocation_command.show(lib, argv, modificators)
            ticket_command.show(lib, argv, modificators)
        elif (sub_cmd == "ref"):
            constraint_ref(argv)
        elif (sub_cmd == "rule"):
            constraint_rule(argv)
        else:
            usage.constraint()
            sys.exit(1)
    except LibraryError as e:
        utils.process_library_reports(e.args)
    except CmdLineInputError as e:
        utils.exit_on_cmdline_input_errror(e, "resource", sub_cmd)