def location_remove(argv): # This code was originally merged in the location_add function and was # documented to take 1 or 4 arguments: # location remove <id> [<resource id> <node> <score>] # However it has always ignored all arguments but constraint id. Therefore # this command / function has no use as it can be fully replaced by "pcs # constraint remove" which also removes constraints by id. For now I keep # things as they are but we should solve this when moving these functions # to pcs.lib. if len(argv) != 1: usage.constraint(["location remove"]) sys.exit(1) constraint_id = argv.pop(0) dom, constraintsElement = getCurrentConstraints() elementsToRemove = [] for rsc_loc in constraintsElement.getElementsByTagName('rsc_location'): if constraint_id == rsc_loc.getAttribute("id"): elementsToRemove.append(rsc_loc) if (len(elementsToRemove) == 0): utils.err("resource location id: " + constraint_id + " not found.") for etr in elementsToRemove: constraintsElement.removeChild(etr) utils.replace_cib_configuration(dom)
def colocation_rm(argv): elementFound = False if len(argv) < 2: usage.constraint() sys.exit(1) (dom, constraintsElement) = getCurrentConstraints() resource1 = argv[0] resource2 = argv[1] for co_loc in constraintsElement.getElementsByTagName('rsc_colocation')[:]: if co_loc.getAttribute("rsc") == resource1 and co_loc.getAttribute( "with-rsc") == resource2: constraintsElement.removeChild(co_loc) elementFound = True if co_loc.getAttribute("rsc") == resource2 and co_loc.getAttribute( "with-rsc") == resource1: constraintsElement.removeChild(co_loc) elementFound = True if elementFound == True: utils.replace_cib_configuration(dom) else: print("No matching resources found in ordering list")
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)
def remove_constraints_containing(resource_id,output=False,constraints_element = None, passed_dom=None): constraints,set_constraints = find_constraints_containing(resource_id, passed_dom) for c in constraints: if output == True: print("Removing Constraint - " + c) if constraints_element != None: constraint_rm([c], True, constraints_element, passed_dom=passed_dom) else: constraint_rm([c], passed_dom=passed_dom) if len(set_constraints) != 0: (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 == True: 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)
def order_rm(argv): if len(argv) == 0: usage.constraint() sys.exit(1) elementFound = False (dom,constraintsElement) = getCurrentConstraints() for resource in argv: for ord_loc in constraintsElement.getElementsByTagName('rsc_order')[:]: if ord_loc.getAttribute("first") == resource or ord_loc.getAttribute("then") == resource: constraintsElement.removeChild(ord_loc) elementFound = True resource_refs_to_remove = [] for ord_set in constraintsElement.getElementsByTagName('resource_ref'): if ord_set.getAttribute("id") == resource: resource_refs_to_remove.append(ord_set) elementFound = True for res_ref in resource_refs_to_remove: res_set = res_ref.parentNode res_order = res_set.parentNode res_ref.parentNode.removeChild(res_ref) if len(res_set.getElementsByTagName('resource_ref')) <= 0: res_set.parentNode.removeChild(res_set) if len(res_order.getElementsByTagName('resource_set')) <= 0: res_order.parentNode.removeChild(res_order) if elementFound == True: utils.replace_cib_configuration(dom) else: utils.err("No matching resources found in ordering list")
def set_node_utilization(node, argv): cib = utils.get_cib_dom() node_el = utils.dom_get_node(cib, node) if node_el is None: if utils.usefile: utils.err("Unable to find a node: {0}".format(node)) for attrs in utils.getNodeAttributesFromPacemaker(): if attrs.name == node and attrs.type == "remote": node_attrs = attrs break else: utils.err("Unable to find a node: {0}".format(node)) nodes_section_list = cib.getElementsByTagName("nodes") if len(nodes_section_list) == 0: utils.err("Unable to get nodes section of cib") dom = nodes_section_list[0].ownerDocument node_el = dom.createElement("node") node_el.setAttribute("id", node_attrs.id) node_el.setAttribute("type", node_attrs.type) node_el.setAttribute("uname", node_attrs.name) nodes_section_list[0].appendChild(node_el) utils.dom_update_utilization(node_el, prepare_options(argv), "nodes-") utils.replace_cib_configuration(cib)
def colocation_rm(lib, argv, modifiers): """ Options: * -f - CIB file """ del lib modifiers.ensure_only_supported("-f") elementFound = False if len(argv) < 2: raise CmdLineInputError() (dom, constraintsElement) = getCurrentConstraints() resource1 = argv[0] resource2 = argv[1] for co_loc in constraintsElement.getElementsByTagName('rsc_colocation')[:]: if (co_loc.getAttribute("rsc") == resource1 and co_loc.getAttribute("with-rsc") == resource2): constraintsElement.removeChild(co_loc) elementFound = True if (co_loc.getAttribute("rsc") == resource2 and co_loc.getAttribute("with-rsc") == resource1): constraintsElement.removeChild(co_loc) elementFound = True if elementFound: utils.replace_cib_configuration(dom) else: print("No matching resources found in ordering list")
def location_remove(lib, argv, modifiers): """ Options: * -f - CIB file """ # This code was originally merged in the location_add function and was # documented to take 1 or 4 arguments: # location remove <id> [<resource id> <node> <score>] # However it has always ignored all arguments but constraint id. Therefore # this command / function has no use as it can be fully replaced by "pcs # constraint remove" which also removes constraints by id. For now I keep # things as they are but we should solve this when moving these functions # to pcs.lib. del lib modifiers.ensure_only_supported("-f") if len(argv) != 1: raise CmdLineInputError() constraint_id = argv.pop(0) dom, constraintsElement = getCurrentConstraints() elementsToRemove = [] for rsc_loc in constraintsElement.getElementsByTagName('rsc_location'): if constraint_id == rsc_loc.getAttribute("id"): elementsToRemove.append(rsc_loc) if not elementsToRemove: utils.err("resource location id: " + constraint_id + " not found.") for etr in elementsToRemove: constraintsElement.removeChild(etr) utils.replace_cib_configuration(dom)
def run_role_delete(argv): if len(argv) < 1: usage.acl(["role delete"]) sys.exit(1) role_id = argv.pop(0) dom = utils.get_cib_dom() found = False for elem in dom.getElementsByTagName("acl_role"): if elem.getAttribute("id") == role_id: found = True elem.parentNode.removeChild(elem) break if not found: utils.err("unable to find acl role: %s" % role_id) # Remove any references to this role in acl_target or acl_group for elem in dom.getElementsByTagName("role"): if elem.getAttribute("id") == role_id: user_group = elem.parentNode user_group.removeChild(elem) if "--autodelete" in utils.pcs_options: if not user_group.getElementsByTagName("role"): user_group.parentNode.removeChild(user_group) utils.replace_cib_configuration(dom)
def set_property(lib, argv, modifiers): """ Options: * --force - allow unknown options * -f - CIB file """ del lib modifiers.ensure_only_supported( "--force", "-f", # The hint is defined to print error messages which point users to the # changes section in pcs manpage. # To be removed in the next significant version. hint_syntax_changed=modifiers.is_specified("--node"), ) if not argv: raise CmdLineInputError() prop_def_dict = utils.get_cluster_properties_definition() failed = False forced = modifiers.get("--force") properties = {} for arg in argv: args = arg.split("=") if len(args) != 2: utils.err("invalid property format: '{0}'".format(arg), False) failed = True elif not args[0]: utils.err("empty property name: '{0}'".format(arg), False) failed = True elif forced or args[1].strip() == "": properties[args[0]] = args[1] else: try: if utils.is_valid_cluster_property(prop_def_dict, args[0], args[1]): properties[args[0]] = args[1] else: utils.err( "invalid value of property: '{0}', (use --force to " "override)".format(arg), False, ) failed = True except utils.UnknownPropertyException: utils.err( "unknown cluster property: '{0}', (use --force to " "override)".format(args[0]), False, ) failed = True if failed: sys.exit(1) cib_dom = utils.get_cib_dom() for prop, value in properties.items(): utils.set_cib_property(prop, value, cib_dom) utils.replace_cib_configuration(cib_dom)
def constraint_rule(argv): if len(argv) < 2: usage.constraint("rule") sys.exit(1) found = False command = argv.pop(0) constraint_id = None if command == "add": constraint_id = argv.pop(0) cib = utils.get_cib_dom() constraint = utils.dom_get_element_with_id( cib.getElementsByTagName("constraints")[0], "rsc_location", constraint_id ) if not constraint: utils.err("Unable to find constraint: " + constraint_id) options, rule_argv = rule_utils.parse_argv(argv) rule_utils.dom_rule_add(constraint, options, rule_argv) location_rule_check_duplicates(cib, constraint) utils.replace_cib_configuration(cib) elif command in ["remove","delete"]: cib = utils.get_cib_etree() temp_id = argv.pop(0) constraints = cib.find('.//constraints') loc_cons = cib.findall(str('.//rsc_location')) for loc_con in loc_cons: for rule in loc_con: if rule.get("id") == temp_id: if len(loc_con) > 1: print("Removing Rule: {0}".format(rule.get("id"))) loc_con.remove(rule) found = True break else: print( "Removing Constraint: {0}".format(loc_con.get("id")) ) constraints.remove(loc_con) found = True break if found == True: break if found: utils.replace_cib_configuration(cib) else: utils.err("unable to find rule with id: %s" % temp_id) else: usage.constraint("rule") sys.exit(1)
def set_node_utilization(node, argv): cib = utils.get_cib_dom() node_el = utils.dom_get_node(cib, node) if node_el is None: utils.err("Unable to find a node: {0}".format(node)) utils.dom_update_utilization( node_el, utils.convert_args_to_tuples(argv), "nodes-" ) utils.replace_cib_configuration(cib)
def stonith_level_rm(level, node, devices): dom = utils.get_cib_dom() if devices != "": node_devices_combo = node + "," + devices else: node_devices_combo = node ft = dom.getElementsByTagName("fencing-topology") if len(ft) == 0: utils.err( "unable to remove fencing level, fencing level for node: %s, at level: %s, with device: %s doesn't exist" % (node, level, devices)) else: ft = ft[0] fls = ft.getElementsByTagName("fencing-level") if node != "": if devices != "": found = False for fl in fls: if fl.getAttribute("target") == node and fl.getAttribute( "index") == level and fl.getAttribute( "devices") == devices: found = True break if fl.getAttribute("index") == level and fl.getAttribute( "devices") == node_devices_combo: found = True break if found == False: utils.err( "unable to remove fencing level, fencing level for node: %s, at level: %s, with device: %s doesn't exist" % (node, level, devices)) fl.parentNode.removeChild(fl) else: for fl in fls: if fl.getAttribute("index") == level and ( fl.getAttribute("target") == node or fl.getAttribute("devices") == node): fl.parentNode.removeChild(fl) else: for fl in fls: if fl.getAttribute("index") == level: parent = fl.parentNode parent.removeChild(fl) if len(parent.getElementsByTagName("fencing-level")) == 0: parent.parentNode.removeChild(parent) break utils.replace_cib_configuration(dom)
def constraint_rm(argv, returnStatus=False, constraintsElement=None, passed_dom=None): if len(argv) < 1: usage.constraint() sys.exit(1) bad_constraint = False if len(argv) != 1: for arg in argv: if not constraint_rm([arg], True, passed_dom=passed_dom): bad_constraint = True if bad_constraint: sys.exit(1) return else: c_id = argv.pop(0) elementFound = False if not constraintsElement: (dom, constraintsElement) = getCurrentConstraints(passed_dom) use_cibadmin = True else: use_cibadmin = False for co in constraintsElement.childNodes[:]: if co.nodeType != xml.dom.Node.ELEMENT_NODE: continue if co.getAttribute("id") == c_id: constraintsElement.removeChild(co) elementFound = True if not elementFound: for rule in constraintsElement.getElementsByTagName("rule")[:]: if rule.getAttribute("id") == c_id: elementFound = True parent = rule.parentNode parent.removeChild(rule) if len(parent.getElementsByTagName("rule")) == 0: parent.parentNode.removeChild(parent) if elementFound == True: if passed_dom: return dom if use_cibadmin: utils.replace_cib_configuration(dom) if returnStatus: return True else: utils.err("Unable to find constraint - '%s'" % c_id, False) if returnStatus: return False sys.exit(1)
def set_property(lib, argv, modifiers): """ Options: * --force - allow unknown options * -f - CIB file """ del lib modifiers.ensure_only_supported( "--force", "-f", ) if not argv: raise CmdLineInputError() prop_def_dict = utils.get_cluster_properties_definition() failed = False forced = modifiers.get("--force") properties = {} for arg in argv: args = arg.split("=") if len(args) != 2: utils.err("invalid property format: '{0}'".format(arg), False) failed = True elif not args[0]: utils.err("empty property name: '{0}'".format(arg), False) failed = True elif forced or args[1].strip() == "": properties[args[0]] = args[1] else: try: if utils.is_valid_cluster_property(prop_def_dict, args[0], args[1]): properties[args[0]] = args[1] else: utils.err( "invalid value of property: '{0}', (use --force to " "override)".format(arg), False, ) failed = True except utils.UnknownPropertyException: utils.err( "unknown cluster property: '{0}', (use --force to " "override)".format(args[0]), False, ) failed = True if failed: sys.exit(1) cib_dom = utils.get_cib_dom() for prop, value in properties.items(): utils.set_cib_property(prop, value, cib_dom) utils.replace_cib_configuration(cib_dom)
def config_checkpoint_restore(argv): if len(argv) != 1: usage.config(["checkpoint", "restore"]) sys.exit(1) cib_path = os.path.join(settings.cib_dir, "cib-%s.raw" % argv[0]) try: snapshot_dom = parse(cib_path) except Exception as e: utils.err("unable to read the checkpoint: %s" % e) utils.replace_cib_configuration(snapshot_dom)
def set_property(lib, argv, modifiers): """ Options: * --force - allow unknown options * -f - CIB file """ del lib modifiers.ensure_only_supported("--force", "-f") if not argv: raise CmdLineInputError() prop_def_dict = utils.get_cluster_properties_definition() failed = False forced = modifiers.get("--force") properties = {} for arg in argv: args = arg.split('=') if len(args) != 2: utils.err("invalid property format: '{0}'".format(arg), False) failed = True elif not args[0]: utils.err("empty property name: '{0}'".format(arg), False) failed = True elif forced or args[1].strip() == "": properties[args[0]] = args[1] else: try: if utils.is_valid_cluster_property( prop_def_dict, args[0], args[1] ): properties[args[0]] = args[1] else: utils.err( "invalid value of property: '{0}', (use --force to " "override)".format(arg), False ) failed = True except utils.UnknownPropertyException: utils.err( "unknown cluster property: '{0}', (use --force to " "override)".format(args[0]), False ) failed = True if failed: sys.exit(1) cib_dom = utils.get_cib_dom() for prop, value in properties.items(): utils.set_cib_property(prop, value, cib_dom) utils.replace_cib_configuration(cib_dom)
def constraint_rm(argv,returnStatus=False, constraintsElement=None, passed_dom=None): if len(argv) < 1: usage.constraint() sys.exit(1) bad_constraint = False if len(argv) != 1: for arg in argv: if not constraint_rm([arg],True, passed_dom=passed_dom): bad_constraint = True if bad_constraint: sys.exit(1) return else: c_id = argv.pop(0) elementFound = False if not constraintsElement: (dom, constraintsElement) = getCurrentConstraints(passed_dom) use_cibadmin = True else: use_cibadmin = False for co in constraintsElement.childNodes[:]: if co.nodeType != xml.dom.Node.ELEMENT_NODE: continue if co.getAttribute("id") == c_id: constraintsElement.removeChild(co) elementFound = True if not elementFound: for rule in constraintsElement.getElementsByTagName("rule")[:]: if rule.getAttribute("id") == c_id: elementFound = True parent = rule.parentNode parent.removeChild(rule) if len(parent.getElementsByTagName("rule")) == 0: parent.parentNode.removeChild(parent) if elementFound == True: if passed_dom: return dom if use_cibadmin: utils.replace_cib_configuration(dom) if returnStatus: return True else: utils.err("Unable to find constraint - '%s'" % c_id, False) if returnStatus: return False sys.exit(1)
def set_property(argv): if not argv: usage.property(['set']) sys.exit(1) prop_def_dict = utils.get_cluster_properties_definition() nodes_attr = "--node" in utils.pcs_options failed = False forced = "--force" in utils.pcs_options properties = {} for arg in argv: args = arg.split('=') if len(args) != 2: utils.err("invalid property format: '{0}'".format(arg), False) failed = True elif not args[0]: utils.err("empty property name: '{0}'".format(arg), False) failed = True elif nodes_attr or forced or args[1].strip() == "": properties[args[0]] = args[1] else: try: if utils.is_valid_cluster_property( prop_def_dict, args[0], args[1] ): properties[args[0]] = args[1] else: utils.err( "invalid value of property: '{0}', (use --force to " "override)".format(arg), False ) failed = True except utils.UnknownPropertyException: utils.err( "unknown cluster property: '{0}', (use --force to " "override)".format(args[0]), False ) failed = True if failed: sys.exit(1) if nodes_attr: for prop, value in properties.items(): utils.set_node_attribute(prop, value, utils.pcs_options["--node"]) else: cib_dom = utils.get_cib_dom() for prop, value in properties.items(): utils.set_cib_property(prop, value, cib_dom) utils.replace_cib_configuration(cib_dom)
def unset_property(argv): if len(argv) < 1: usage.property() sys.exit(1) if "--node" in utils.pcs_options: for arg in argv: utils.set_node_attribute(arg, "",utils.pcs_options["--node"]) else: cib_dom = utils.get_cib_dom() for arg in argv: utils.set_cib_property(arg, "", cib_dom) utils.replace_cib_configuration(cib_dom)
def unset_property(lib, argv, modifiers): """ Options: * --force - no error when removing not existing properties * -f - CIB file """ modifiers.ensure_only_supported("--force", "-f") if len(argv) < 1: raise CmdLineInputError() cib_dom = utils.get_cib_dom() for arg in argv: utils.set_cib_property(arg, "", cib_dom) utils.replace_cib_configuration(cib_dom)
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)
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
def unset_property(lib, argv, modifiers): """ Options: * --force - no error when removing not existing properties * -f - CIB file """ del lib modifiers.ensure_only_supported("--force", "-f") if not argv: raise CmdLineInputError() cib_dom = utils.get_cib_dom() for arg in argv: utils.set_cib_property(arg, "", cib_dom) utils.replace_cib_configuration(cib_dom)
def run_permission_delete(argv): dom = utils.get_cib_dom() if len(argv) < 1: usage.acl(["permission delete"]) sys.exit(1) perm_id = argv.pop(0) found = False for elem in dom.getElementsByTagName("acl_permission"): if elem.getAttribute("id") == perm_id: elem.parentNode.removeChild(elem) found = True if not found: utils.err("Unable to find permission with id: %s" % perm_id) utils.replace_cib_configuration(dom)
def config_checkpoint_restore(dummy_lib, argv, modifiers): """ Options: * -f - CIB file, a checkpoint will be restored into a specified file """ modifiers.ensure_only_supported("-f") if len(argv) != 1: usage.config(["checkpoint", "restore"]) sys.exit(1) cib_path = os.path.join(settings.cib_dir, "cib-%s.raw" % argv[0]) try: snapshot_dom = parse(cib_path) except Exception as e: utils.err("unable to read the checkpoint: %s" % e) utils.replace_cib_configuration(snapshot_dom)
def stonith_level_rm(level, node, devices): dom = utils.get_cib_dom() if devices != "": node_devices_combo = node + "," + devices else: node_devices_combo = node ft = dom.getElementsByTagName("fencing-topology") if len(ft) == 0: utils.err("unable to remove fencing level, fencing level for node: %s, at level: %s, with device: %s doesn't exist" % (node,level,devices)) else: ft = ft[0] fls = ft.getElementsByTagName("fencing-level") if node != "": if devices != "": found = False for fl in fls: if fl.getAttribute("target") == node and fl.getAttribute("index") == level and fl.getAttribute("devices") == devices: found = True break if fl.getAttribute("index") == level and fl.getAttribute("devices") == node_devices_combo: found = True break if found == False: utils.err("unable to remove fencing level, fencing level for node: %s, at level: %s, with device: %s doesn't exist" % (node,level,devices)) fl.parentNode.removeChild(fl) else: for fl in fls: if fl.getAttribute("index") == level and (fl.getAttribute("target") == node or fl.getAttribute("devices") == node): fl.parentNode.removeChild(fl) else: for fl in fls: if fl.getAttribute("index") == level: parent = fl.parentNode parent.removeChild(fl) if len(parent.getElementsByTagName("fencing-level")) == 0: parent.parentNode.removeChild(parent) break utils.replace_cib_configuration(dom)
def config_checkpoint_restore(lib, argv, modifiers): """ Options: * -f - CIB file, a checkpoint will be restored into a specified file """ # pylint: disable=broad-except del lib modifiers.ensure_only_supported("-f") if len(argv) != 1: usage.config(["checkpoint restore"]) sys.exit(1) cib_path = os.path.join(settings.cib_dir, "cib-%s.raw" % argv[0]) try: snapshot_dom = parse(cib_path) except Exception as e: utils.err("unable to read the checkpoint: %s" % e) utils.replace_cib_configuration(snapshot_dom)
def set_node_utilization(node, argv): """ Commandline options: * -f - CIB file """ nvpair_dict = prepare_options(argv) if not nvpair_dict: return only_removing = True for value in nvpair_dict.values(): if value != "": only_removing = False break cib = utils.get_cib_dom() node_el = utils.dom_get_node(cib, node) if node_el is None: if utils.usefile: utils.err("Unable to find a node: {0}".format(node)) for attrs in utils.getNodeAttributesFromPacemaker(): if attrs.name == node and attrs.type == "remote": node_attrs = attrs break else: utils.err("Unable to find a node: {0}".format(node)) nodes_section_list = cib.getElementsByTagName("nodes") if not nodes_section_list: utils.err("Unable to get nodes section of cib") if only_removing: # Do not create new node if we are only removing values from it. return dom = nodes_section_list[0].ownerDocument node_el = dom.createElement("node") node_el.setAttribute("id", node_attrs.id) node_el.setAttribute("type", node_attrs.type) node_el.setAttribute("uname", node_attrs.name) nodes_section_list[0].appendChild(node_el) utils.dom_update_utilization(node_el, nvpair_dict, "nodes-") utils.replace_cib_configuration(cib)
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)
def order_rm(lib, argv, modifiers): """ Options: * -f - CIB file """ del lib modifiers.ensure_only_supported("-f") if not argv: raise CmdLineInputError() elementFound = False (dom, constraintsElement) = getCurrentConstraints() for resource in argv: for ord_loc in constraintsElement.getElementsByTagName('rsc_order')[:]: if ( ord_loc.getAttribute("first") == resource or ord_loc.getAttribute("then") == resource ): constraintsElement.removeChild(ord_loc) elementFound = True resource_refs_to_remove = [] for ord_set in constraintsElement.getElementsByTagName('resource_ref'): if ord_set.getAttribute("id") == resource: resource_refs_to_remove.append(ord_set) elementFound = True for res_ref in resource_refs_to_remove: res_set = res_ref.parentNode res_order = res_set.parentNode res_ref.parentNode.removeChild(res_ref) if not res_set.getElementsByTagName('resource_ref'): res_set.parentNode.removeChild(res_set) if not res_order.getElementsByTagName('resource_set'): res_order.parentNode.removeChild(res_order) if elementFound: utils.replace_cib_configuration(dom) else: utils.err("No matching resources found in ordering list")
def run_role_assign(argv): if len(argv) < 2: usage.acl(["role assign"]) sys.exit(1) if len(argv) == 2: role_id = argv[0] ug_id = argv[1] elif len(argv) > 2 and argv[1] == "to": role_id = argv[0] ug_id = argv[2] else: usage.acl(["role assign"]) sys.exit(1) dom = utils.get_cib_dom() found = False for role in dom.getElementsByTagName("acl_role"): if role.getAttribute("id") == role_id: found = True break if not found: utils.err("cannot find role: %s" % role_id) found = False for ug in dom.getElementsByTagName("acl_target") + dom.getElementsByTagName("acl_group"): if ug.getAttribute("id") == ug_id: found = True break if not found: utils.err("cannot find user or group: %s" % ug_id) for current_role in ug.getElementsByTagName("role"): if current_role.getAttribute("id") == role_id: utils.err(role_id + " is already assigned to " + ug_id) new_role = dom.createElement("role") new_role.setAttribute("id", role_id) ug.appendChild(new_role) utils.replace_cib_configuration(dom)
def unset_property(lib, argv, modifiers): """ Options: * --force - no error when removing not existing properties * -f - CIB file """ del lib modifiers.ensure_only_supported( "--force", "-f", # The hint is defined to print error messages which point users to the # changes section in pcs manpage. # To be removed in the next significant version. hint_syntax_changed=modifiers.is_specified("--node") ) if not argv: raise CmdLineInputError() cib_dom = utils.get_cib_dom() for arg in argv: utils.set_cib_property(arg, "", cib_dom) utils.replace_cib_configuration(cib_dom)
def stonith_level_clear(node = None): dom = utils.get_cib_dom() ft = dom.getElementsByTagName("fencing-topology") if len(ft) == 0: return if node == None: ft = ft[0] childNodes = ft.childNodes[:] for node in childNodes: node.parentNode.removeChild(node) else: fls = dom.getElementsByTagName("fencing-level") if len(fls) == 0: return for fl in fls: if fl.getAttribute("target") == node or fl.getAttribute("devices") == node: fl.parentNode.removeChild(fl) utils.replace_cib_configuration(dom)
def stonith_level_clear(node=None): dom = utils.get_cib_dom() ft = dom.getElementsByTagName("fencing-topology") if len(ft) == 0: return if node == None: ft = ft[0] childNodes = ft.childNodes[:] for node in childNodes: node.parentNode.removeChild(node) else: fls = dom.getElementsByTagName("fencing-level") if len(fls) == 0: return for fl in fls: if fl.getAttribute("target") == node or fl.getAttribute( "devices") == node: fl.parentNode.removeChild(fl) utils.replace_cib_configuration(dom)
def constraint_resource_update(old_id, passed_dom=None): dom = utils.get_cib_dom() if passed_dom is None else passed_dom new_id = None clone_ms_parent = utils.dom_get_resource_clone_ms_parent(dom, old_id) if clone_ms_parent: new_id = clone_ms_parent.getAttribute("id") if new_id: constraints = dom.getElementsByTagName("rsc_location") constraints += dom.getElementsByTagName("rsc_order") constraints += dom.getElementsByTagName("rsc_colocation") attrs_to_update = ["rsc", "first", "then", "with-rsc"] for constraint in constraints: for attr in attrs_to_update: if constraint.getAttribute(attr) == old_id: constraint.setAttribute(attr, new_id) if passed_dom is None: utils.replace_cib_configuration(dom) if passed_dom: return dom
def constraint_resource_update(old_id, passed_dom=None): dom = utils.get_cib_dom() if passed_dom is None else passed_dom new_id = None clone_ms_parent = utils.dom_get_resource_clone_ms_parent(dom, old_id) if clone_ms_parent: new_id = clone_ms_parent.getAttribute("id") if new_id: constraints = dom.getElementsByTagName("rsc_location") constraints += dom.getElementsByTagName("rsc_order") constraints += dom.getElementsByTagName("rsc_colocation") attrs_to_update=["rsc","first","then", "with-rsc"] for constraint in constraints: for attr in attrs_to_update: if constraint.getAttribute(attr) == old_id: constraint.setAttribute(attr, new_id) if passed_dom is None: utils.replace_cib_configuration(dom) if passed_dom: return dom
def colocation_rm(argv): elementFound = False if len(argv) < 2: usage.constraint() sys.exit(1) (dom,constraintsElement) = getCurrentConstraints() resource1 = argv[0] resource2 = argv[1] for co_loc in constraintsElement.getElementsByTagName('rsc_colocation')[:]: if co_loc.getAttribute("rsc") == resource1 and co_loc.getAttribute("with-rsc") == resource2: constraintsElement.removeChild(co_loc) elementFound = True if co_loc.getAttribute("rsc") == resource2 and co_loc.getAttribute("with-rsc") == resource1: constraintsElement.removeChild(co_loc) elementFound = True if elementFound == True: utils.replace_cib_configuration(dom) else: print("No matching resources found in ordering list")
def run_role_unassign(argv): if len(argv) < 2: usage.acl(["role unassign"]) sys.exit(1) role_id = argv.pop(0) if len(argv) > 1 and argv[0] == "from": ug_id = argv[1] else: ug_id = argv[0] dom = utils.get_cib_dom() found = False for ug in dom.getElementsByTagName("acl_target") + dom.getElementsByTagName("acl_group"): if ug.getAttribute("id") == ug_id: found = True break if not found: utils.err("cannot find user or group: %s" % ug_id) found = False for current_role in ug.getElementsByTagName("role"): if current_role.getAttribute("id") == role_id: found = True current_role.parentNode.removeChild(current_role) break if not found: utils.err("cannot find role: %s, assigned to user/group: %s" % (role_id, ug_id)) if "--autodelete" in utils.pcs_options: if not ug.getElementsByTagName("role"): ug.parentNode.removeChild(ug) utils.replace_cib_configuration(dom)
def acl_target(argv,group=False): if len(argv) < 2: if group: usage.acl(["group"]) sys.exit(1) else: usage.acl(["user"]) sys.exit(1) dom = utils.get_cib_dom() acls = utils.get_acls(dom) command = argv.pop(0) tug_id = argv.pop(0) if command == "create": # pcsd parses the error message in order to determine whether the id is # assigned to user/group or some other cib element if group and utils.dom_get_element_with_id(dom, "acl_group", tug_id): utils.err("group %s already exists" % tug_id) if not group and utils.dom_get_element_with_id(dom, "acl_target", tug_id): utils.err("user %s already exists" % tug_id) if utils.does_id_exist(dom,tug_id): utils.err(tug_id + " already exists") if group: element = dom.createElement("acl_group") else: element = dom.createElement("acl_target") element.setAttribute("id", tug_id) acls.appendChild(element) for role in argv: if not utils.dom_get_element_with_id(acls, "acl_role", role): utils.err("cannot find acl role: %s" % role) r = dom.createElement("role") r.setAttribute("id", role) element.appendChild(r) utils.replace_cib_configuration(dom) elif command == "delete": found = False if group: elist = dom.getElementsByTagName("acl_group") else: elist = dom.getElementsByTagName("acl_target") for elem in elist: if elem.getAttribute("id") == tug_id: found = True elem.parentNode.removeChild(elem) break if not found: if group: utils.err("unable to find acl group: %s" % tug_id) else: utils.err("unable to find acl target/user: %s" % tug_id) utils.replace_cib_configuration(dom) else: if group: usage.acl(["group"]) else: usage.acl(["user"]) sys.exit(1)
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)
def location_add(argv,rm=False): if len(argv) < 4 and (rm == False or len(argv) < 1): usage.constraint() sys.exit(1) constraint_id = argv.pop(0) # If we're removing, we only care about the id if (rm == True): resource_name = "" node = "" score = "" else: id_valid, id_error = utils.validate_xml_id(constraint_id, 'constraint id') if not id_valid: utils.err(id_error) resource_name = argv.pop(0) node = argv.pop(0) score = argv.pop(0) options = [] # For now we only allow setting resource-discovery if len(argv) > 0: for arg in argv: if '=' in arg: options.append(arg.split('=',1)) else: print("Error: bad option '%s'" % arg) usage.constraint(["location add"]) sys.exit(1) if options[-1][0] != "resource-discovery" and "--force" not in utils.pcs_options: utils.err("bad option '%s', use --force to override" % options[-1][0]) resource_valid, resource_error, correct_id \ = utils.validate_constraint_resource( utils.get_cib_dom(), resource_name ) if "--autocorrect" in utils.pcs_options and correct_id: resource_name = correct_id elif not resource_valid: utils.err(resource_error) if not utils.is_score(score): utils.err("invalid score '%s', use integer or INFINITY or -INFINITY" % score) # Verify current constraint doesn't already exist # If it does we replace it with the new constraint (dom,constraintsElement) = getCurrentConstraints() elementsToRemove = [] # If the id matches, or the rsc & node match, then we replace/remove for rsc_loc in constraintsElement.getElementsByTagName('rsc_location'): if (constraint_id == rsc_loc.getAttribute("id")) or \ (rsc_loc.getAttribute("rsc") == resource_name and \ rsc_loc.getAttribute("node") == node and not rm): elementsToRemove.append(rsc_loc) for etr in elementsToRemove: constraintsElement.removeChild(etr) if (rm == True and len(elementsToRemove) == 0): utils.err("resource location id: " + constraint_id + " not found.") if (not rm): element = dom.createElement("rsc_location") element.setAttribute("id",constraint_id) element.setAttribute("rsc",resource_name) element.setAttribute("node",node) element.setAttribute("score",score) for option in options: element.setAttribute(option[0], option[1]) constraintsElement.appendChild(element) utils.replace_cib_configuration(dom)
def location_add(lib, argv, modifiers): """ Options: * --force - allow unknown options, allow constraint for any resource type * -f - CIB file """ del lib modifiers.ensure_only_supported("--force", "-f") if len(argv) < 4: raise CmdLineInputError() constraint_id = argv.pop(0) rsc_type, rsc_value = parse_args.parse_typed_arg( argv.pop(0), [RESOURCE_TYPE_RESOURCE, RESOURCE_TYPE_REGEXP], RESOURCE_TYPE_RESOURCE) node = argv.pop(0) score = argv.pop(0) options = [] # For now we only allow setting resource-discovery if argv: for arg in argv: if '=' in arg: options.append(arg.split('=', 1)) else: raise CmdLineInputError(f"bad option '{arg}'") if (options[-1][0] != "resource-discovery" and not modifiers.get("--force")): utils.err("bad option '%s', use --force to override" % options[-1][0]) id_valid, id_error = utils.validate_xml_id(constraint_id, 'constraint id') if not id_valid: utils.err(id_error) if not utils.is_score(score): utils.err("invalid score '%s', use integer or INFINITY or -INFINITY" % score) required_version = None if [x for x in options if x[0] == "resource-discovery"]: required_version = 2, 2, 0 if rsc_type == RESOURCE_TYPE_REGEXP: required_version = 2, 6, 0 if required_version: dom = utils.cluster_upgrade_to_version(required_version) else: dom = utils.get_cib_dom() if rsc_type == RESOURCE_TYPE_RESOURCE: rsc_valid, rsc_error, dummy_correct_id = ( utils.validate_constraint_resource(dom, rsc_value)) if not rsc_valid: utils.err(rsc_error) # Verify that specified node exists in the cluster if not (modifiers.is_specified("-f") or modifiers.get("--force")): lib_env = utils.get_lib_env() existing_nodes = get_existing_nodes_names( corosync_conf=lib_env.get_corosync_conf(), cib=lib_env.get_cib(), ) if node not in existing_nodes: raise error(f"Node '{node}' does not seem to be in the cluster" ", use --force to override") else: warn(LOCATION_NODE_VALIDATION_SKIP_MSG) # Verify current constraint doesn't already exist # If it does we replace it with the new constraint dummy_dom, constraintsElement = getCurrentConstraints(dom) elementsToRemove = [] # If the id matches, or the rsc & node match, then we replace/remove for rsc_loc in constraintsElement.getElementsByTagName('rsc_location'): # pylint: disable=too-many-boolean-expressions if (rsc_loc.getAttribute("id") == constraint_id or (rsc_loc.getAttribute("node") == node and ((RESOURCE_TYPE_RESOURCE == rsc_type and rsc_loc.getAttribute("rsc") == rsc_value) or (RESOURCE_TYPE_REGEXP == rsc_type and rsc_loc.getAttribute("rsc-pattern") == rsc_value)))): elementsToRemove.append(rsc_loc) for etr in elementsToRemove: constraintsElement.removeChild(etr) element = dom.createElement("rsc_location") element.setAttribute("id", constraint_id) if rsc_type == RESOURCE_TYPE_RESOURCE: element.setAttribute("rsc", rsc_value) elif rsc_type == RESOURCE_TYPE_REGEXP: element.setAttribute("rsc-pattern", rsc_value) element.setAttribute("node", node) element.setAttribute("score", score) for option in options: element.setAttribute(option[0], option[1]) constraintsElement.appendChild(element) utils.replace_cib_configuration(dom)
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)
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)
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)
def constraint_rule(lib, argv, modifiers): """ Options: * -f - CIB file * --force - allow duplicate constraints, only for add command NOTE: modifiers check is in subcommand """ del lib if len(argv) < 2: raise CmdLineInputError() found = False command = argv.pop(0) constraint_id = None if command == "add": modifiers.ensure_only_supported("-f", "--force") constraint_id = argv.pop(0) cib = utils.get_cib_dom() constraint = utils.dom_get_element_with_id( cib.getElementsByTagName("constraints")[0], "rsc_location", constraint_id) if not constraint: utils.err("Unable to find constraint: " + constraint_id) options, rule_argv = rule_utils.parse_argv(argv) rule_utils.dom_rule_add(constraint, options, rule_argv) location_rule_check_duplicates(cib, constraint, modifiers.get("--force")) utils.replace_cib_configuration(cib) elif command in ["remove", "delete"]: modifiers.ensure_only_supported("-f") cib = utils.get_cib_etree() temp_id = argv.pop(0) constraints = cib.find('.//constraints') loc_cons = cib.findall(str('.//rsc_location')) for loc_con in loc_cons: for rule in loc_con: if rule.get("id") == temp_id: if len(loc_con) > 1: print("Removing Rule: {0}".format(rule.get("id"))) loc_con.remove(rule) found = True break else: print("Removing Constraint: {0}".format( loc_con.get("id"))) constraints.remove(loc_con) found = True break if found: break if found: utils.replace_cib_configuration(cib) else: utils.err("unable to find rule with id: %s" % temp_id) else: raise CmdLineInputError()
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()
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)
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)