Beispiel #1
0
def stonith_level_add(level, node, devices):
    dom = utils.get_cib_dom()

    if not re.search(r'^\d+$', level) or re.search(r'^0+$', level):
        utils.err("invalid level '{0}', use a positive integer".format(level))
    level = level.lstrip('0')
    if "--force" not in utils.pcs_options:
        for dev in devices.split(","):
            if not utils.is_stonith_resource(dev):
                utils.err("%s is not a stonith id (use --force to override)" % dev)
        if not utils.is_pacemaker_node(node) and not utils.is_corosync_node(node):
            utils.err("%s is not currently a node (use --force to override)" % node)

    ft = dom.getElementsByTagName("fencing-topology")
    if len(ft) == 0:
        conf = dom.getElementsByTagName("configuration")[0]
        ft = dom.createElement("fencing-topology")
        conf.appendChild(ft)
    else:
        ft = ft[0]

    fls = ft.getElementsByTagName("fencing-level")
    for fl in fls:
        if fl.getAttribute("target") == node and fl.getAttribute("index") == level and fl.getAttribute("devices") == devices:
            utils.err("unable to add fencing level, fencing level for node: %s, at level: %s, with device: %s already exists" % (node,level,devices))

    new_fl = dom.createElement("fencing-level")
    ft.appendChild(new_fl)
    new_fl.setAttribute("target", node)
    new_fl.setAttribute("index", level)
    new_fl.setAttribute("devices", devices)
    new_fl.setAttribute("id", utils.find_unique_id(dom, "fl-" + node +"-" + level))

    utils.replace_cib_configuration(dom)
Beispiel #2
0
def location_rule(argv):
    if len(argv) < 3:
        usage.constraint(["location", "rule"])
        sys.exit(1)

    res_name = argv.pop(0)
    resource_valid, resource_error, correct_id \
        = utils.validate_constraint_resource(utils.get_cib_dom(), res_name)
    if "--autocorrect" in utils.pcs_options and correct_id:
        res_name = correct_id
    elif not resource_valid:
        utils.err(resource_error)

    argv.pop(0) # pop "rule"

    options, rule_argv = rule_utils.parse_argv(argv, {"constraint-id": None, "resource-discovery": None,})

    # If resource-discovery is specified, we use it with the rsc_location
    # element not the rule
    if "resource-discovery" in options and options["resource-discovery"]:
        utils.checkAndUpgradeCIB(2,2,0)
        cib, constraints = getCurrentConstraints(utils.get_cib_dom())
        lc = cib.createElement("rsc_location")
        lc.setAttribute("resource-discovery", options.pop("resource-discovery"))
    else:
        cib, constraints = getCurrentConstraints(utils.get_cib_dom())
        lc = cib.createElement("rsc_location")


    constraints.appendChild(lc)
    if options.get("constraint-id"):
        id_valid, id_error = utils.validate_xml_id(
            options["constraint-id"], 'constraint id'
        )
        if not id_valid:
            utils.err(id_error)
        if utils.does_id_exist(cib, options["constraint-id"]):
            utils.err(
                "id '%s' is already in use, please specify another one"
                % options["constraint-id"]
            )
        lc.setAttribute("id", options["constraint-id"])
        del options["constraint-id"]
    else:
        lc.setAttribute("id", utils.find_unique_id(cib, "location-" + res_name))
    lc.setAttribute("rsc", res_name)

    rule_utils.dom_rule_add(lc, options, rule_argv)
    location_rule_check_duplicates(constraints, lc)
    utils.replace_cib_configuration(cib)
Beispiel #3
0
def location_rule(argv):
    if len(argv) < 3:
        usage.constraint(["location", "rule"])
        sys.exit(1)

    res_name = argv.pop(0)
    resource_valid, resource_error, correct_id \
        = utils.validate_constraint_resource(utils.get_cib_dom(), res_name)
    if "--autocorrect" in utils.pcs_options and correct_id:
        res_name = correct_id
    elif not resource_valid:
        utils.err(resource_error)

    argv.pop(0) # pop "rule"

    options, rule_argv = rule_utils.parse_argv(argv, {"constraint-id": None, "resource-discovery": None,})

    # If resource-discovery is specified, we use it with the rsc_location
    # element not the rule
    if "resource-discovery" in options and options["resource-discovery"]:
        utils.checkAndUpgradeCIB(2,2,0)
        cib, constraints = getCurrentConstraints(utils.get_cib_dom())
        lc = cib.createElement("rsc_location")
        lc.setAttribute("resource-discovery", options.pop("resource-discovery"))
    else:
        cib, constraints = getCurrentConstraints(utils.get_cib_dom())
        lc = cib.createElement("rsc_location")


    constraints.appendChild(lc)
    if options.get("constraint-id"):
        id_valid, id_error = utils.validate_xml_id(
            options["constraint-id"], 'constraint id'
        )
        if not id_valid:
            utils.err(id_error)
        if utils.does_id_exist(cib, options["constraint-id"]):
            utils.err(
                "id '%s' is already in use, please specify another one"
                % options["constraint-id"]
            )
        lc.setAttribute("id", options["constraint-id"])
        del options["constraint-id"]
    else:
        lc.setAttribute("id", utils.find_unique_id(cib, "location-" + res_name))
    lc.setAttribute("rsc", res_name)

    rule_utils.dom_rule_add(lc, options, rule_argv)
    location_rule_check_duplicates(constraints, lc)
    utils.replace_cib_configuration(cib)
Beispiel #4
0
def set_add_resource_sets(elem, sets, cib):
    allowed_options = {
        "sequential": ("true", "false"),
        "require-all": ("true", "false"),
        "action" : OPTIONS_ACTION,
        "role" : OPTIONS_ROLE,
    }

    for o_set in sets:
        set_id = "pcs_rsc_set"
        res_set = cib.createElement("resource_set")
        elem.appendChild(res_set)
        for opts in o_set:
            if opts.find("=") != -1:
                key,val = opts.split("=")
                if key not in allowed_options:
                    utils.err(
                        "invalid option '%s', allowed options are: %s"
                        % (key, ", ".join(sorted(allowed_options.keys())))
                    )
                if val not in allowed_options[key]:
                    utils.err(
                        "invalid value '%s' of option '%s', allowed values are: %s"
                        % (val, key, ", ".join(allowed_options[key]))
                    )
                res_set.setAttribute(key, val)
            else:
                res_valid, res_error, correct_id \
                    = utils.validate_constraint_resource(cib, opts)
                if "--autocorrect" in utils.pcs_options and correct_id:
                    opts = correct_id
                elif not res_valid:
                    utils.err(res_error)
                se = cib.createElement("resource_ref")
                res_set.appendChild(se)
                se.setAttribute("id", opts)
                set_id = set_id + "_" + opts
        res_set.setAttribute("id", utils.find_unique_id(cib, set_id))
    if "--force" not in utils.pcs_options:
        duplicates = set_constraint_find_duplicates(cib, elem)
        if duplicates:
            utils.err(
                "duplicate constraint already exists, use --force to override\n"
                + "\n".join([
                    "  " + set_constraint_el_to_string(dup, True)
                    for dup in duplicates
                ])
            )
Beispiel #5
0
def stonith_level_add(level, node, devices):
    dom = utils.get_cib_dom()

    if not re.search(r'^\d+$', level) or re.search(r'^0+$', level):
        utils.err("invalid level '{0}', use a positive integer".format(level))
    level = level.lstrip('0')
    if "--force" not in utils.pcs_options:
        for dev in devices.split(","):
            if not utils.is_stonith_resource(dev):
                utils.err("%s is not a stonith id (use --force to override)" %
                          dev)
        corosync_nodes = []
        if utils.hasCorosyncConf():
            corosync_nodes = utils.getNodesFromCorosyncConf()
        pacemaker_nodes = utils.getNodesFromPacemaker()
        if node not in corosync_nodes and node not in pacemaker_nodes:
            utils.err("%s is not currently a node (use --force to override)" %
                      node)

    ft = dom.getElementsByTagName("fencing-topology")
    if len(ft) == 0:
        conf = dom.getElementsByTagName("configuration")[0]
        ft = dom.createElement("fencing-topology")
        conf.appendChild(ft)
    else:
        ft = ft[0]

    fls = ft.getElementsByTagName("fencing-level")
    for fl in fls:
        if fl.getAttribute("target") == node and fl.getAttribute(
                "index") == level and fl.getAttribute("devices") == devices:
            utils.err(
                "unable to add fencing level, fencing level for node: %s, at level: %s, with device: %s already exists"
                % (node, level, devices))

    new_fl = dom.createElement("fencing-level")
    ft.appendChild(new_fl)
    new_fl.setAttribute("target", node)
    new_fl.setAttribute("index", level)
    new_fl.setAttribute("devices", devices)
    new_fl.setAttribute("id",
                        utils.find_unique_id(dom, "fl-" + node + "-" + level))

    utils.replace_cib_configuration(dom)
Beispiel #6
0
 def add_element(self, parent, tag_name, element_id):
     dom = parent.ownerDocument
     child = parent.appendChild(dom.createElement(tag_name))
     child.setAttribute("id", utils.find_unique_id(dom, element_id))
     return child
Beispiel #7
0
 def add_element(parent, tag_name, element_id):
     dom = parent.ownerDocument
     child = parent.appendChild(dom.createElement(tag_name))
     child.setAttribute("id", utils.find_unique_id(dom, element_id))
     return child
Beispiel #8
0
def location_rule(lib, argv, modifiers):
    """
    Options:
      * -f - CIB file
      * --force - allow constraint on any resource type, allow duplicate
        constraints
    """
    del lib
    modifiers.ensure_only_supported("-f", "--force")
    if len(argv) < 3:
        usage.constraint(["location", "rule"])
        sys.exit(1)

    rsc_type, rsc_value = parse_args.parse_typed_arg(
        argv.pop(0), [RESOURCE_TYPE_RESOURCE, RESOURCE_TYPE_REGEXP],
        RESOURCE_TYPE_RESOURCE)
    argv.pop(0)  # pop "rule"
    options, rule_argv = rule_utils.parse_argv(argv, {
        "constraint-id": None,
        "resource-discovery": None,
    })
    resource_discovery = ("resource-discovery" in options
                          and options["resource-discovery"])

    required_version = None
    if 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)

    cib, constraints = getCurrentConstraints(dom)
    lc = cib.createElement("rsc_location")

    # If resource-discovery is specified, we use it with the rsc_location
    # element not the rule
    if resource_discovery:
        lc.setAttribute("resource-discovery",
                        options.pop("resource-discovery"))

    constraints.appendChild(lc)
    if options.get("constraint-id"):
        id_valid, id_error = utils.validate_xml_id(options["constraint-id"],
                                                   'constraint id')
        if not id_valid:
            utils.err(id_error)
        if utils.does_id_exist(dom, options["constraint-id"]):
            utils.err("id '%s' is already in use, please specify another one" %
                      options["constraint-id"])
        lc.setAttribute("id", options["constraint-id"])
        del options["constraint-id"]
    else:
        lc.setAttribute(
            "id",
            utils.find_unique_id(dom, sanitize_id("location-" + rsc_value)))
    if rsc_type == RESOURCE_TYPE_RESOURCE:
        lc.setAttribute("rsc", rsc_value)
    elif rsc_type == RESOURCE_TYPE_REGEXP:
        lc.setAttribute("rsc-pattern", rsc_value)

    rule_utils.dom_rule_add(lc, options, rule_argv)
    location_rule_check_duplicates(constraints, lc, modifiers.get("--force"))
    utils.replace_cib_configuration(cib)
Beispiel #9
0
def order_add(argv, modifiers):
    """
    Commandline options:
      * -f - CIB file
      * --force - allow constraint for any resource, allow duplicate constraints
    """
    if len(argv) < 2:
        raise CmdLineInputError()

    resource1 = argv.pop(0)
    resource2 = argv.pop(0)

    cib_dom = utils.get_cib_dom()
    resource_valid, resource_error, dummy_correct_id \
        = utils.validate_constraint_resource(cib_dom, resource1)
    if not resource_valid:
        utils.err(resource_error)
    resource_valid, resource_error, dummy_correct_id \
        = utils.validate_constraint_resource(cib_dom, resource2)
    if not resource_valid:
        utils.err(resource_error)

    order_options = []
    id_specified = False
    sym = None
    for arg in argv:
        if arg == "symmetrical":
            sym = "true"
        elif arg == "nonsymmetrical":
            sym = "false"
        elif "=" in arg:
            name, value = arg.split("=", 1)
            if name == "id":
                id_valid, id_error = utils.validate_xml_id(
                    value, 'constraint id')
                if not id_valid:
                    utils.err(id_error)
                if utils.does_id_exist(cib_dom, value):
                    utils.err(
                        "id '%s' is already in use, please specify another one"
                        % value)
                id_specified = True
                order_options.append((name, value))
            elif name == "symmetrical":
                if value.lower() in OPTIONS_SYMMETRICAL:
                    sym = value.lower()
                else:
                    utils.err(
                        "invalid symmetrical value '%s', allowed values are: %s"
                        % (value, ", ".join(OPTIONS_SYMMETRICAL)))
            else:
                order_options.append((name, value))
    if sym:
        order_options.append(("symmetrical", sym))

    options = ""
    if order_options:
        options = " (Options: %s)" % " ".join([
            "%s=%s" % (name, value)
            for name, value in order_options if name not in ("kind", "score")
        ])

    scorekind = "kind: Mandatory"
    id_suffix = "mandatory"
    for opt in order_options:
        if opt[0] == "score":
            scorekind = "score: " + opt[1]
            id_suffix = opt[1]
            break
        if opt[0] == "kind":
            scorekind = "kind: " + opt[1]
            id_suffix = opt[1]
            break

    if not id_specified:
        order_id = "order-" + resource1 + "-" + resource2 + "-" + id_suffix
        order_id = utils.find_unique_id(cib_dom, order_id)
        order_options.append(("id", order_id))

    (dom, constraintsElement) = getCurrentConstraints()
    element = dom.createElement("rsc_order")
    element.setAttribute("first", resource1)
    element.setAttribute("then", resource2)
    for order_opt in order_options:
        element.setAttribute(order_opt[0], order_opt[1])
    constraintsElement.appendChild(element)
    if not modifiers.get("--force"):
        duplicates = order_find_duplicates(constraintsElement, element)
        if duplicates:
            utils.err(
                "duplicate constraint already exists, use --force to override\n"
                + "\n".join([
                    "  " + constraint_order.console_report.constraint_plain(
                        {"options": dict(dup.attributes.items())}, True)
                    for dup in duplicates
                ]))
    print("Adding " + resource1 + " " + resource2 + " (" + scorekind + ")" +
          options)

    utils.replace_cib_configuration(dom)
Beispiel #10
0
def colocation_add(lib, argv, modifiers):
    """
    Options:
      * -f - CIB file
      * --force - allow constraint on any resource, allow duplicate constraints
    """
    del lib
    modifiers.ensure_only_supported("-f", "--force")
    if len(argv) < 3:
        raise CmdLineInputError()

    role1 = ""
    role2 = ""

    if argv[2] == "with":
        role1 = argv.pop(0).lower().capitalize()
        resource1 = argv.pop(0)
    elif argv[1] == "with":
        resource1 = argv.pop(0)
    else:
        raise CmdLineInputError()

    argv.pop(0)  # Pop 'with'

    if not argv:
        raise CmdLineInputError()
    elif len(argv) == 1:
        resource2 = argv.pop(0)
    else:
        if utils.is_score_or_opt(argv[1]):
            resource2 = argv.pop(0)
        else:
            role2 = argv.pop(0).lower().capitalize()
            resource2 = argv.pop(0)

    score, nv_pairs = parse_score_options(argv)

    cib_dom = utils.get_cib_dom()
    resource_valid, resource_error, dummy_correct_id \
        = utils.validate_constraint_resource(cib_dom, resource1)
    if not resource_valid:
        utils.err(resource_error)
    resource_valid, resource_error, dummy_correct_id \
        = utils.validate_constraint_resource(cib_dom, resource2)
    if not resource_valid:
        utils.err(resource_error)

    id_in_nvpairs = None
    for name, value in nv_pairs:
        if name == "id":
            id_valid, id_error = utils.validate_xml_id(value, 'constraint id')
            if not id_valid:
                utils.err(id_error)
            if utils.does_id_exist(cib_dom, value):
                utils.err(
                    "id '%s' is already in use, please specify another one" %
                    value)
            id_in_nvpairs = True
    if not id_in_nvpairs:
        nv_pairs.append(
            ("id",
             utils.find_unique_id(
                 cib_dom,
                 "colocation-%s-%s-%s" % (resource1, resource2, score))))

    (dom, constraintsElement) = getCurrentConstraints(cib_dom)

    # If one role is specified, the other should default to "started"
    if role1 != "" and role2 == "":
        role2 = DEFAULT_ROLE
    if role2 != "" and role1 == "":
        role1 = DEFAULT_ROLE
    element = dom.createElement("rsc_colocation")
    element.setAttribute("rsc", resource1)
    element.setAttribute("with-rsc", resource2)
    element.setAttribute("score", score)
    if role1 != "":
        element.setAttribute("rsc-role", role1)
    if role2 != "":
        element.setAttribute("with-rsc-role", role2)
    for nv_pair in nv_pairs:
        element.setAttribute(nv_pair[0], nv_pair[1])
    if not modifiers.get("--force"):
        duplicates = colocation_find_duplicates(constraintsElement, element)
        if duplicates:
            utils.err(
                "duplicate constraint already exists, use --force to override\n"
                + "\n".join([
                    "  " +
                    constraint_colocation.console_report.constraint_plain(
                        {"options": dict(dup.attributes.items())}, True)
                    for dup in duplicates
                ]))
    constraintsElement.appendChild(element)
    utils.replace_cib_configuration(dom)
Beispiel #11
0
def order_add(argv,returnElementOnly=False):
    if len(argv) < 2:
        usage.constraint()
        sys.exit(1)

    resource1 = argv.pop(0)
    resource2 = argv.pop(0)

    cib_dom = utils.get_cib_dom()
    resource_valid, resource_error, correct_id \
        = utils.validate_constraint_resource(cib_dom, resource1)
    if "--autocorrect" in utils.pcs_options and correct_id:
        resource1 = correct_id
    elif not resource_valid:
        utils.err(resource_error)
    resource_valid, resource_error, correct_id \
        = utils.validate_constraint_resource(cib_dom, resource2)
    if "--autocorrect" in utils.pcs_options and correct_id:
        resource2 = correct_id
    elif not resource_valid:
        utils.err(resource_error)

    order_options = []
    id_specified = False
    sym = None
    for arg in argv:
        if arg == "symmetrical":
            sym = "true"
        elif arg == "nonsymmetrical":
            sym = "false"
        elif "=" in arg:
            name, value = arg.split("=", 1)
            if name == "id":
                id_valid, id_error = utils.validate_xml_id(value, 'constraint id')
                if not id_valid:
                    utils.err(id_error)
                if utils.does_id_exist(cib_dom, value):
                    utils.err(
                        "id '%s' is already in use, please specify another one"
                        % value
                    )
                id_specified = True
                order_options.append((name, value))
            elif name == "symmetrical":
                if value.lower() in OPTIONS_SYMMETRICAL:
                    sym = value.lower()
                else:
                    utils.err(
                        "invalid symmetrical value '%s', allowed values are: %s"
                        % (value, ", ".join(OPTIONS_SYMMETRICAL))
                    )
            else:
                order_options.append((name, value))
    if sym:
        order_options.append(("symmetrical", sym))

    options = ""
    if order_options:
        options = " (Options: %s)" % " ".join([
            "%s=%s" % (name, value)
                for name, value in order_options
                    if name not in ("kind", "score")
        ])

    scorekind = "kind: Mandatory"
    id_suffix = "mandatory"
    for opt in order_options:
        if opt[0] == "score":
            scorekind = "score: " + opt[1]
            id_suffix = opt[1]
            break
        if opt[0] == "kind":
            scorekind = "kind: " + opt[1]
            id_suffix = opt[1]
            break

    if not id_specified:
        order_id = "order-" + resource1 + "-" + resource2 + "-" + id_suffix
        order_id = utils.find_unique_id(cib_dom, order_id)
        order_options.append(("id", order_id))

    (dom,constraintsElement) = getCurrentConstraints()
    element = dom.createElement("rsc_order")
    element.setAttribute("first",resource1)
    element.setAttribute("then",resource2)
    for order_opt in order_options:
        element.setAttribute(order_opt[0], order_opt[1])
    constraintsElement.appendChild(element)
    if "--force" not in utils.pcs_options:
        duplicates = order_find_duplicates(constraintsElement, element)
        if duplicates:
            utils.err(
                "duplicate constraint already exists, use --force to override\n"
                + "\n".join([
                    "  " + constraint_order.console_report.constraint_plain(
                            {"options": dict(dup.attributes.items())},
                            True
                        ) for dup in duplicates
                ])
            )
    print(
        "Adding " + resource1 + " " + resource2 + " ("+scorekind+")" + options
    )

    if returnElementOnly == False:
        utils.replace_cib_configuration(dom)
    else:
        return element.toxml()
Beispiel #12
0
def colocation_add(argv):
    if len(argv) < 2:
        usage.constraint()
        sys.exit(1)

    role1 = ""
    role2 = ""
    if len(argv) > 2:
        if not utils.is_score_or_opt(argv[2]):
            if argv[2] == "with":
                role1 = argv.pop(0).lower().capitalize()
                resource1 = argv.pop(0)
            else:
                resource1 = argv.pop(0)

            argv.pop(0) # Pop 'with'

            if len(argv) == 1:
                resource2 = argv.pop(0)
            else:
                if utils.is_score_or_opt(argv[1]):
                    resource2 = argv.pop(0)
                else:
                    role2 = argv.pop(0).lower().capitalize()
                    resource2 = argv.pop(0)
        else:
            resource1 = argv.pop(0)
            resource2 = argv.pop(0)
    else:
        resource1 = argv.pop(0)
        resource2 = argv.pop(0)

    cib_dom = utils.get_cib_dom()
    resource_valid, resource_error, correct_id \
        = utils.validate_constraint_resource(cib_dom, resource1)
    if "--autocorrect" in utils.pcs_options and correct_id:
        resource1 = correct_id
    elif not resource_valid:
        utils.err(resource_error)
    resource_valid, resource_error, correct_id \
        = utils.validate_constraint_resource(cib_dom, resource2)
    if "--autocorrect" in utils.pcs_options and correct_id:
        resource2 = correct_id
    elif not resource_valid:
        utils.err(resource_error)

    score,nv_pairs = parse_score_options(argv)
    id_in_nvpairs = None
    for name, value in nv_pairs:
        if name == "id":
            id_valid, id_error = utils.validate_xml_id(value, 'constraint id')
            if not id_valid:
                utils.err(id_error)
            if utils.does_id_exist(cib_dom, value):
                utils.err(
                    "id '%s' is already in use, please specify another one"
                    % value
                )
            id_in_nvpairs = True
    if not id_in_nvpairs:
        nv_pairs.append((
            "id",
            utils.find_unique_id(
                cib_dom,
                "colocation-%s-%s-%s" % (resource1, resource2, score)
            )
        ))

    (dom,constraintsElement) = getCurrentConstraints(cib_dom)

# If one role is specified, the other should default to "started"
    if role1 != "" and role2 == "":
        role2 = DEFAULT_ROLE
    if role2 != "" and role1 == "":
        role1 = DEFAULT_ROLE
    element = dom.createElement("rsc_colocation")
    element.setAttribute("rsc",resource1)
    element.setAttribute("with-rsc",resource2)
    element.setAttribute("score",score)
    if role1 != "":
        element.setAttribute("rsc-role", role1)
    if role2 != "":
        element.setAttribute("with-rsc-role", role2)
    for nv_pair in nv_pairs:
        element.setAttribute(nv_pair[0], nv_pair[1])
    if "--force" not in utils.pcs_options:
        duplicates = colocation_find_duplicates(constraintsElement, element)
        if duplicates:
            utils.err(
                "duplicate constraint already exists, use --force to override\n"
                + "\n".join([
                    "  " + constraint_colocation.console_report.constraint_plain(
                            {"options": dict(dup.attributes.items())},
                            True
                        )
                    for dup in duplicates
                ])
            )
    constraintsElement.appendChild(element)
    utils.replace_cib_configuration(dom)
Beispiel #13
0
def colocation_add(lib, argv, modifiers):
    """
    Options:
      * -f - CIB file
      * --force - allow constraint on any resource, allow duplicate constraints
    """
    def _parse_score_options(argv):
        # When passed an array of arguments if the first argument doesn't have
        # an '=' then it's the score, otherwise they're all arguments. Return a
        # tuple with the score and array of name,value pairs
        """
        Commandline options: no options
        """
        if not argv:
            return SCORE_INFINITY, []
        score = SCORE_INFINITY if "=" in argv[0] else argv.pop(0)
        # create a list of 2-tuples (name, value)
        arg_array = [
            parse_args.split_option(arg, allow_empty_value=False)
            for arg in argv
        ]
        return score, arg_array

    def _validate_and_prepare_role(role):
        role_cleaned = role.lower().capitalize()
        if role_cleaned not in RESOURCE_ROLES:
            utils.err(
                "invalid role value '{0}', allowed values are: '{1}'".format(
                    role, "', '".join(RESOURCE_ROLES)))
        return role_cleaned

    del lib
    modifiers.ensure_only_supported("-f", "--force")
    if len(argv) < 3:
        raise CmdLineInputError()

    role1 = ""
    role2 = ""

    if argv[2] == "with":
        role1 = _validate_and_prepare_role(argv.pop(0))
        resource1 = argv.pop(0)
    elif argv[1] == "with":
        resource1 = argv.pop(0)
    else:
        raise CmdLineInputError()

    if argv.pop(0) != "with":
        raise CmdLineInputError()
    if "with" in argv:
        raise CmdLineInputError(
            message="Multiple 'with's cannot be specified.",
            hint=(
                "Use the 'pcs constraint colocation set' command if you want "
                "to create a constraint for more than two resources."),
            show_both_usage_and_message=True)

    if not argv:
        raise CmdLineInputError()
    if len(argv) == 1:
        resource2 = argv.pop(0)
    else:
        if utils.is_score_or_opt(argv[1]):
            resource2 = argv.pop(0)
        else:
            role2 = _validate_and_prepare_role(argv.pop(0))
            resource2 = argv.pop(0)

    score, nv_pairs = _parse_score_options(argv)

    cib_dom = utils.get_cib_dom()
    _validate_constraint_resource(cib_dom, resource1)
    _validate_constraint_resource(cib_dom, resource2)

    id_in_nvpairs = None
    for name, value in nv_pairs:
        if name == "id":
            id_valid, id_error = utils.validate_xml_id(value, 'constraint id')
            if not id_valid:
                utils.err(id_error)
            if utils.does_id_exist(cib_dom, value):
                utils.err(
                    "id '%s' is already in use, please specify another one" %
                    value)
            id_in_nvpairs = True
    if not id_in_nvpairs:
        nv_pairs.append(
            ("id",
             utils.find_unique_id(
                 cib_dom,
                 "colocation-%s-%s-%s" % (resource1, resource2, score))))

    (dom, constraintsElement) = getCurrentConstraints(cib_dom)

    # If one role is specified, the other should default to "started"
    if role1 != "" and role2 == "":
        role2 = DEFAULT_ROLE
    if role2 != "" and role1 == "":
        role1 = DEFAULT_ROLE
    element = dom.createElement("rsc_colocation")
    element.setAttribute("rsc", resource1)
    element.setAttribute("with-rsc", resource2)
    element.setAttribute("score", score)
    if role1 != "":
        element.setAttribute("rsc-role", role1)
    if role2 != "":
        element.setAttribute("with-rsc-role", role2)
    for nv_pair in nv_pairs:
        element.setAttribute(nv_pair[0], nv_pair[1])
    if not modifiers.get("--force"):
        duplicates = colocation_find_duplicates(constraintsElement, element)
        if duplicates:
            utils.err(
                "duplicate constraint already exists, use --force to override\n"
                + "\n".join([
                    "  " +
                    constraint_colocation.console_report.constraint_plain(
                        {"options": dict(dup.attributes.items())}, True)
                    for dup in duplicates
                ]))
    constraintsElement.appendChild(element)
    utils.replace_cib_configuration(dom)
Beispiel #14
0
def order_set(argv):
    setoptions = []
    for i in range(len(argv)):
        if argv[i] == "setoptions":
            setoptions = argv[i+1:]
            argv[i:] = []
            break

    argv.insert(0, "set")
    resource_sets = set_args_into_array(argv)
    if not check_empty_resource_sets(resource_sets):
        usage.constraint(["order set"])
        sys.exit(1)
    cib, constraints = getCurrentConstraints(utils.get_cib_dom())

    attributes = []
    id_specified = False
    for opt in setoptions:
        if "=" not in opt:
            utils.err("missing value of '%s' option" % opt)
        name, value = opt.split("=", 1)
        if name == "id":
            id_valid, id_error = utils.validate_xml_id(value, 'constraint id')
            if not id_valid:
                utils.err(id_error)
            if utils.does_id_exist(cib, value):
                utils.err(
                    "id '%s' is already in use, please specify another one"
                    % value
                )
            id_specified = True
            attributes.append((name, value))
        elif name == "kind":
            normalized_value = value.lower().capitalize()
            if normalized_value not in OPTIONS_KIND:
                utils.err(
                    "invalid kind value '%s', allowed values are: %s"
                    % (value, ", ".join(OPTIONS_KIND))
                )
            attributes.append((name, normalized_value))
        elif name == "symmetrical":
            if value.lower() not in OPTIONS_SYMMETRICAL:
                utils.err(
                    "invalid symmetrical value '%s', allowed values are: %s"
                    % (value, ", ".join(OPTIONS_SYMMETRICAL))
                )
            attributes.append((name, value.lower()))
        else:
            utils.err(
                "invalid option '%s', allowed options are: %s"
                % (name, "kind, symmetrical, id")
            )

    if not id_specified:
        order_id = "pcs_rsc_order"
        for a in argv:
            if "=" not in a:
                order_id += "_" + a
        attributes.append(("id", utils.find_unique_id(cib, order_id)))

    rsc_order = cib.createElement("rsc_order")
    for name, value in attributes:
        rsc_order.setAttribute(name, value)
    set_add_resource_sets(rsc_order, resource_sets, cib)
    constraints.appendChild(rsc_order)
    utils.replace_cib_configuration(cib)
Beispiel #15
0
def colocation_set(argv):
    setoptions = []
    for i in range(len(argv)):
        if argv[i] == "setoptions":
            setoptions = argv[i+1:]
            argv[i:] = []
            break

    argv.insert(0, "set")
    resource_sets = set_args_into_array(argv)
    if not check_empty_resource_sets(resource_sets):
        usage.constraint(["colocation set"])
        sys.exit(1)
    cib, constraints = getCurrentConstraints(utils.get_cib_dom())

    attributes = []
    score_options = ("score", "score-attribute", "score-attribute-mangle")
    score_specified = False
    id_specified = False
    for opt in setoptions:
        if "=" not in opt:
            utils.err("missing value of '%s' option" % opt)
        name, value = opt.split("=", 1)
        if name == "id":
            id_valid, id_error = utils.validate_xml_id(value, 'constraint id')
            if not id_valid:
                utils.err(id_error)
            if utils.does_id_exist(cib, value):
                utils.err(
                    "id '%s' is already in use, please specify another one"
                    % value
                )
            id_specified = True
            attributes.append((name, value))
        elif name in score_options:
            if score_specified:
                utils.err("you cannot specify multiple score options")
            if name == "score" and not utils.is_score(value):
                utils.err(
                    "invalid score '%s', use integer or INFINITY or -INFINITY"
                    % value
                )
            score_specified = True
            attributes.append((name, value))
        else:
            utils.err(
                "invalid option '%s', allowed options are: %s"
                % (name, ", ".join(score_options + ("id",)))
            )

    if not score_specified:
        attributes.append(("score", "INFINITY"))
    if not id_specified:
        colocation_id = "pcs_rsc_colocation"
        for a in argv:
            if "=" not in a:
                colocation_id += "_" + a
        attributes.append(("id", utils.find_unique_id(cib, colocation_id)))

    rsc_colocation = cib.createElement("rsc_colocation")
    for name, value in attributes:
        rsc_colocation.setAttribute(name, value)
    set_add_resource_sets(rsc_colocation, resource_sets, cib)
    constraints.appendChild(rsc_colocation)
    utils.replace_cib_configuration(cib)
Beispiel #16
0
def location_rule(argv):
    if len(argv) < 3:
        usage.constraint(["location", "rule"])
        sys.exit(1)

    rsc_type, rsc_value = parse_args.parse_typed_arg(
        argv.pop(0),
        [RESOURCE_TYPE_RESOURCE, RESOURCE_TYPE_REGEXP],
        RESOURCE_TYPE_RESOURCE
    )
    argv.pop(0) # pop "rule"
    options, rule_argv = rule_utils.parse_argv(
        argv,
        {
            "constraint-id": None,
            "resource-discovery": None,
        }
    )
    resource_discovery = (
        "resource-discovery" in options
        and
        options["resource-discovery"]
    )

    required_version = None
    if 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, correct_id = utils.validate_constraint_resource(
            dom, rsc_value
        )
        if "--autocorrect" in utils.pcs_options and correct_id:
            rsc_value = correct_id
        elif not rsc_valid:
            utils.err(rsc_error)

    cib, constraints = getCurrentConstraints(dom)
    lc = cib.createElement("rsc_location")

    # If resource-discovery is specified, we use it with the rsc_location
    # element not the rule
    if resource_discovery:
        lc.setAttribute("resource-discovery", options.pop("resource-discovery"))

    constraints.appendChild(lc)
    if options.get("constraint-id"):
        id_valid, id_error = utils.validate_xml_id(
            options["constraint-id"], 'constraint id'
        )
        if not id_valid:
            utils.err(id_error)
        if utils.does_id_exist(dom, options["constraint-id"]):
            utils.err(
                "id '%s' is already in use, please specify another one"
                % options["constraint-id"]
            )
        lc.setAttribute("id", options["constraint-id"])
        del options["constraint-id"]
    else:
        lc.setAttribute(
            "id",
            utils.find_unique_id(dom, sanitize_id("location-" + rsc_value))
        )
    if rsc_type == RESOURCE_TYPE_RESOURCE:
        lc.setAttribute("rsc", rsc_value)
    elif rsc_type == RESOURCE_TYPE_REGEXP:
        lc.setAttribute("rsc-pattern", rsc_value)

    rule_utils.dom_rule_add(lc, options, rule_argv)
    location_rule_check_duplicates(constraints, lc)
    utils.replace_cib_configuration(cib)