def get_ra(r):
    """
    Argument is either an xml resource tag with class, provider and type attributes,
    or a CLI style class:provider:type string.
    """
    if isinstance(r, str):
        cls, provider, typ = disambiguate_ra_type(r)
    else:
        cls, provider, typ = r.get('class'), r.get('provider'), r.get('type')
    # note order of arguments!
    return RAInfo(cls, typ, provider) @utils.memoize
def get_properties_list():
    try:
        return list(get_properties_meta().params().keys())
    except:
        return [] @utils.memoize
def get_pe_meta():
    return RAInfo(utils.pacemaker_schedulerd(), "metadata") @utils.memoize
def get_properties_meta():
    meta = copy.deepcopy(get_crmd_meta())
    meta.add_ra_params(get_pe_meta())
    meta.add_ra_params(get_cib_meta())
    return meta def ext_cmd(cmd, shell=True):
    cmd = add_sudo(cmd)
    if options.regression_tests:
        print(".EXT", cmd)
    logger.debug("invoke: %s", cmd)
    return subprocess.call(cmd, shell=shell) def safe_open_w(fname):
    if fname == "-":
        f = sys.stdout
    else:
        if not options.batch and os.access(fname, os.F_OK):
            if not ask("File %s exists. Do you want to overwrite it?" % fname):
                return None
        try:
            f = open(fname, "w")
        except IOError as msg:
            logger.error(msg)
            return None
    return f def pipe_string(cmd, s):
    rc = -1  # command failed
    cmd = add_sudo(cmd)
    logger.debug("piping string to %s", cmd)
    if options.regression_tests:
        print(".EXT", cmd)
    p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE)
    try:
        # communicate() expects encoded bytes
        if isinstance(s, str):
            s = s.encode('utf-8')
        p.communicate(s)
        p.wait()
        rc = p.returncode
    except IOError as msg:
        if "Broken pipe" not in str(msg):
            logger.error(msg)
    return rc def safe_close_w(f):
    if f and f != sys.stdout:
        f.close() def crm_msec(t):
    '''
    See lib/common/utils.c:crm_get_msec().
    '''
    convtab = {
        'ms': (1, 1),
        'msec': (1, 1),
        'us': (1, 1000),
        'usec': (1, 1000),
        '': (1000, 1),
        's': (1000, 1),
        'sec': (1000, 1),
        'm': (60*1000, 1),
        'min': (60*1000, 1),
        'h': (60*60*1000, 1),
        'hr': (60*60*1000, 1),
    }
    if not t:
        return -1
    r = re.match(r"\s*(\d+)\s*([a-zA-Z]+)?", t)
    if not r:
        return -1
    if not r.group(2):
        q = ''
    else:
        q = r.group(2).lower()
    try:
        mult, div = convtab[q]
    except KeyError:
        return -1
    return (int(r.group(1))*mult) // div def ask(msg):
    """
    Ask for user confirmation.
    If core.force is true, always return true.
    If not interactive and core.force is false, always return false.
    """
    if config.core.force:
        logger.info("%s [YES]", msg)
        return True
    if not can_ask():
        return False

    msg += ' '
    if msg.endswith('? '):
        msg = msg[:-2] + ' (y/n)? '

    while True:
        try:
            ans = input(msg)
        except EOFError:
            ans = 'n'
        if ans:
            ans = ans[0].lower()
            if ans in 'yn':
                return ans == 'y' def lines2cli(s):
    '''
    Convert a string into a list of lines. Replace continuation
    characters. Strip white space, left and right. Drop empty lines.
    '''
    cl = []
    l = s.split('\n')
    cum = []
    for p in l:
        p = p.strip()
        if p.endswith('\\'):
            p = p.rstrip('\\')
            cum.append(p)
        else:
            cum.append(p)
            cl.append(''.join(cum).strip())
            cum = []
    if cum:  # in case s ends with backslash
        cl.append(''.join(cum))
    return [x for x in cl if x] class olist(list):
    """
    Implements the 'in' operator
    in a case-insensitive manner,
    allowing "if x in olist(...)"
    """
    def __init__(self, keys):
        super(olist, self).__init__([k.lower() for k in keys])

    def __contains__(self, key):
        return super(olist, self).__contains__(key.lower())

    def append(self, key):
        super(olist, self).append(key.lower()) def page_string(s):
    'Page string rendered for TERM.'
    if not s:
        return
    constants.need_reset = True
    w, h = get_winsize()
    if not need_pager(s, w, h):
        print(term_render(s))
    elif not config.core.pager or not can_ask() or options.batch:
        print(term_render(s))
    else:
        pipe_string(get_pager_cmd(), term_render(s).encode('utf-8'))
    constants.need_reset = False @memoize
def cibadmin_can_patch():
    # cibadmin -P doesn't handle comments in <1.1.11 (unless patched)
    return is_min_pcmk_ver("1.1.11") def str2tmp(_str, suffix=".pcmk"):
    '''
    Write the given string to a temporary file. Return the name
    of the file.
    '''
    s = to_ascii(_str)
    fd, tmp = mkstemp(suffix=suffix)
    try:
        f = os.fdopen(fd, "w")
    except IOError as msg:
        logger.error(msg)
        return
    f.write(s)
    if not s.endswith('\n'):
        f.write("\n")
    f.close()
    return tmp def ensure_sudo_readable(f):
    # make sure the tempfile is readable to crm_diff (bsc#999683)
    if config.core.user:
        from pwd import getpwnam
        uid = getpwnam(config.core.user).pw_uid
        try:
            os.chown(f, uid, -1)
        except os.error as err:
            logger.error('Failed setting temporary file permissions: %s', err)
            return False
    return True def run_ptest(graph_s, nograph, scores, utilization, actions, verbosity):
    '''
    Pipe graph_s thru ptest(8). Show graph using dotty if requested.
    '''
    actions_filter = "grep LogActions: | grep -vw Leave"
    ptest = "2>&1 %s -x -" % config.core.ptest
    if re.search("simulate", ptest) and \
            not re.search("-[RS]", ptest):
        ptest = "%s -S" % ptest
    if verbosity:
        if actions:
            verbosity = 'v' * max(3, len(verbosity))
        ptest = "%s -%s" % (ptest, verbosity.upper())
    if scores:
        ptest = "%s -s" % ptest
    if utilization:
        ptest = "%s -U" % ptest
    if config.core.dotty and not nograph:
        fd, dotfile = mkstemp()
        ptest = "%s -D %s" % (ptest, dotfile)
    else:
        dotfile = None
    # ptest prints to stderr
    if actions:
        ptest = "%s | %s" % (ptest, actions_filter)
    if options.regression_tests:
        ptest = ">/dev/null %s" % ptest
    logger.debug("invoke: %s", ptest)
    rc, s = get_stdout(ptest, input_s=graph_s)
    if rc != 0:
        logger.debug("'%s' exited with (rc=%d)", ptest, rc)
        if actions and rc == 1:
            logger.warning("No actions found.")
        else:
            logger.warning("Simulation was unsuccessful (RC=%d).", rc)
    if dotfile:
        if os.path.getsize(dotfile) > 0:
            show_dot_graph(dotfile)
        else:
            logger.warning("ptest produced empty dot file")
    else:
        if not nograph:
            logger.info("install graphviz to see a transition graph")
    if s:
        page_string(s)
    return True def is_id_valid(ident):
    """
    Verify that the id follows the definition:
    http://www.w3.org/TR/1999/REC-xml-names-19990114/#ns-qualnames
    """
    if not ident:
        return False
    id_re = r"^[A-Za-z_][\w._-]*$"
    return re.match(id_re, ident) def edit_file(fname):
    'Edit a file.'
    if not fname:
        return
    if not config.core.editor:
        return
    return ext_cmd_nosudo("%s %s" % (config.core.editor, fname)) def get_boolean(opt, dflt=False):
    if not opt:
        return dflt
    return is_boolean_true(opt) def filter_string(cmd, s, stderr_on=True, shell=True):
    rc = -1  # command failed
    outp = ''
    if stderr_on is True:
        stderr = None
    else:
        stderr = subprocess.PIPE
    cmd = add_sudo(cmd)
    logger.debug("pipe through %s", cmd)
    if options.regression_tests:
        print(".EXT", cmd)
    p = subprocess.Popen(cmd,
                         shell=shell,
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=stderr)
    try:
        # bytes expected here
        if isinstance(s, str):
            s = s.encode('utf-8')
        ret = p.communicate(s)
        if stderr_on == 'stdout':
            outp = b"\n".join(ret)
        else:
            outp = ret[0]
        p.wait()
        rc = p.returncode
    except OSError as err:
        if err.errno != os.errno.EPIPE:
            logger.error(err.strerror)
        logger.error("from: %s", cmd)
    except Exception as msg:
        logger.error("from: %s: %s", cmd, str(msg))
    return rc, to_ascii(outp) def is_child_rsc(node):
    return node.tag in constants.children_tags def rsc_constraint(rsc_id, con_elem):
    for attr in list(con_elem.keys()):
        if attr in constants.constraint_rsc_refs \
                and rsc_id == con_elem.get(attr):
            return True
    for rref in con_elem.xpath("resource_set/resource_ref"):
        if rsc_id == rref.get("id"):
            return True
    return False def sanitize_cib(doc):
    xml_processnodes(doc, is_status_node, rmnodes)
    # xml_processnodes(doc, true, printid)
    # xml_processnodes(doc, is_emptynvpairs, rmnodes)
    # xml_processnodes(doc, is_emptyops, rmnodes)
    xml_processnodes(doc, is_entity, rmnodes)
    # xml_processnodes(doc, is_comment, rmnodes)
    xml_processnodes(doc, is_container, sort_container_children)
    xml_processnodes(doc, true, remove_dflt_attrs)
    xml_processnodes(doc, true, remove_text)
    xmltraverse(doc, drop_attr_defaults) def rename_id(node, old_id, new_id):
    if node.get("id") == old_id:
        node.set("id", new_id) def get_interesting_nodes(node, nodes_l):
    '''
    All nodes which can be represented as CIB objects.
    '''
    for c in node.iterchildren():
        if is_cib_element(c):
            nodes_l.append(c)
        get_interesting_nodes(c, nodes_l)
    return nodes_l def is_pref_location(node):
    'Figure out if the location is a node preference.'
    rule_l = node.findall("rule")
    expr_l = node.xpath(".//expression")
    return len(rule_l) == 1 and len(expr_l) == 1 and \
        expr_l[0].get("attribute") == "#uname" and \
        expr_l[0].get("operation") == "eq" def get_topnode(cib_elem, tag):
    "Get configuration element or create/append if there's none."
    conf_elem = cib_elem.find("configuration")
    if conf_elem is None:
        logger.error("no configuration element found!")
        return None
    if tag == "configuration":
        return conf_elem
    e = cib_elem.find("configuration/%s" % tag)
    if e is None:
        logger.debug("create configuration section %s", tag)
        e = etree.SubElement(conf_elem, tag)
    return e def new_cib():
    cib_elem = etree.Element("cib")
    conf_elem = etree.SubElement(cib_elem, "configuration")
    for name in schema.get('sub', "configuration", 'r'):
        etree.SubElement(conf_elem, name)
    return cib_elem def get_rscop_defaults_meta_node(node):
    return get_child_nvset_node(node) def rename_rscref(c_obj, old_id, new_id):
    if rename_rscref_simple(c_obj, old_id, new_id) or \
            rename_rscref_rset(c_obj, old_id, new_id):
        logger.info("modified %s from %s to %s", str(c_obj), old_id, new_id) def is_ms_or_promotable_clone(self, ident):
    '''
    Test if the resource is master-slave.
    '''
    rsc_node = self.rsc2node(ident)
    if rsc_node is None:
        return False
    return is_ms_or_promotable_clone(rsc_node) def silly_constraint(c_node, rsc_id):
    '''
    Remove a constraint from rsc_id to rsc_id.
    Or an invalid one.
    '''
    if c_node.xpath("resource_set/resource_ref"):
        # it's a resource set
        # the resource sets have already been uniq-ed
        cnt = len(c_node.xpath("resource_set/resource_ref"))
        if c_node.tag in ("rsc_location", "rsc_ticket"):  # locations and tickets are never silly
            return cnt < 1
        return cnt <= 1
    cnt = 0  # total count of referenced resources have to be at least two
    rsc_cnt = 0
    for attr in list(c_node.keys()):
        if attr in constants.constraint_rsc_refs:
            cnt += 1
            if c_node.get(attr) == rsc_id:
                rsc_cnt += 1
    if c_node.tag in ("rsc_location", "rsc_ticket"):  # locations and tickets are never silly
        return cnt < 1
    else:
        return rsc_cnt == 2 or cnt < 2 def is_container(node):
    return node.tag in constants.container_tags def fix_comments(e):
    'Make sure that comments start with #'
    celems = [x for x in e.iterchildren() if is_comment(x)]
    for c in celems:
        c.text = c.text.strip()
        if not c.text.startswith("#"):
            c.text = "# %s" % c.text def sanity_check_nvpairs(ident, node, attr_list):
    rc = 0
    for nvpair in node.iterchildren("nvpair"):
        n = nvpair.get("name")
        if n and n not in attr_list:
            logger.warning("%s: unknown attribute '%s'", ident, n)
            rc |= 1
    return rc def merge_nodes(dnode, snode):
    '''
    Import elements from snode into dnode.
    If an element is attributes set (constants.nvpairs_tags) or
    "operations", then merge attributes in the children.
    Otherwise, replace the whole element. (TBD)
    '''
    rc = False  # any changes done?
    if dnode is None or snode is None:
        return rc
    add_children = []
    for sc in snode.iterchildren():
        dc = lookup_node(sc, dnode, ignore_id=True)
        if dc is None:
            if sc.tag in constants.nvpairs_tags or sc.tag == "operations":
                add_children.append(sc)
                rc = True
        elif dc.tag in constants.nvpairs_tags:
            rc = merge_attributes(dc, sc, "nvpair") or rc
        elif dc.tag == "operations":
            rc = merge_attributes(dc, sc, "op") or rc
    for c in add_children:
        dnode.append(copy.deepcopy(c))
    return rc def op2list(node):
    pl = []
    action = ""
    for name in list(node.keys()):
        if name == "name":
            action = node.get(name)
        elif name != "id":  # skip the id
            pl.append([name, node.get(name)])
    if not action:
        logger.error("op is invalid (no name)")
    return action, pl def mk_rsc_type(n):
    """
    Returns prefixless for unique RAs
    """
    ra_type = n.get("type")
    ra_class = n.get("class")
    ra_provider = n.get("provider")
    if unique_ra(ra_type, ra_class, ra_provider):
        ra_class = None
        ra_provider = None
    s1 = s2 = ''
    if ra_class:
        s1 = "%s:" % ra_class
    if ra_provider:
        s2 = "%s:" % ra_provider
    return ''.join((s1, s2, ra_type)) def is_resource(node):
    return node.tag in constants.resource_tags def stuff_comments(node, comments):
    if not comments:
        return
    for s in reversed(comments):
        add_comment(node, s) def is_comment(e):
    return e.tag == etree.Comment def is_constraint(node):
    return node.tag in constants.constraint_tags def read_cib(fun, params=None):
    cib_elem = fun(params)
    if cib_elem is None or cib_elem.tag != "cib":
        return None
    return cib_elem def processing_sort_cli(nl):
    '''
    nl: list of objects (CibObject)
    Returns the given list in order

    TODO: if sort_elements is disabled, only sort to resolve inter-dependencies.
    '''
    def sort_elements(k):
        return _sort_cli_order.get(k.obj_type, _SORT_LAST), k.obj_id

    def sort_type(k):
        return _sort_cli_order.get(k.obj_type, _SORT_LAST)

    return sorted(nl, key=sort_elements if config.core.sort_elements else sort_type) def find_operation(rsc_node, name, interval=None):
    '''
    Setting interval to "non-0" means get the first op with interval
    different from 0.
    Not setting interval at all means get the only matching op, or the
    0 op (if any)
    '''
    matching_name = []
    for ops in rsc_node.findall("operations"):
        matching_name.extend([op for op in ops.iterchildren("op")
                              if op.get("name") == name])
    if interval is None and len(matching_name) == 1:
        return matching_name[0]
    interval = interval or "0"
    for op in matching_name:
        opint = op.get("interval")
        if interval == "non-0" and crm_msec(opint) > 0:
            return op
        if crm_time_cmp(opint, interval) == 0:
            return op
    return None def get_rsc_children_ids(node):
    return [x.get("id")
            for x in node.iterchildren() if is_child_rsc(x)] def is_primitive(node):
    return node.tag == "primitive" def referenced_resources(node):
    if not is_constraint(node):
        return []
    xml_obj_type = node.tag
    rsc_list = []
    if xml_obj_type == "rsc_location" and node.get("rsc"):
        rsc_list = [node.get("rsc")]
    elif node.xpath("resource_set/resource_ref"):
        # resource sets
        rsc_list = [x.get("id")
                    for x in node.xpath("resource_set/resource_ref")]
    elif xml_obj_type == "rsc_colocation":
        rsc_list = [node.get("rsc"), node.get("with-rsc")]
    elif xml_obj_type == "rsc_order":
        rsc_list = [node.get("first"), node.get("then")]
    elif xml_obj_type == "rsc_ticket":
        rsc_list = [node.get("rsc")]
    return [rsc for rsc in rsc_list if rsc is not None] def cibdump2elem(section=None):
    if section:
        cmd = "%s -o %s" % (cib_dump, section)
    else:
        cmd = cib_dump
    rc, outp, errp = sudocall(cmd)
    if rc == 0:
        return text2elem(outp)
    elif rc != constants.cib_no_section_rc:
        logger.error("running %s: %s", cmd, errp)
    return None def processing_sort(nl):
    '''
    It's usually important to process cib objects in this order,
    i.e. simple objects first.

    TODO: if sort_elements is disabled, only sort to resolve inter-dependencies.
    '''
    def sort_elements(k):
        return _sort_xml_order.get(k.tag, _SORT_LAST)

    def sort_type(k):
        return _sort_xml_order.get(k.tag, _SORT_LAST)

    return sorted(nl, key=sort_elements if config.core.sort_elements else sort_type) def get_rsc_ref_ids(node):
    return [x.get("id")
            for x in node.xpath("./resource_ref")] def merge_tmpl_into_prim(prim_node, tmpl_node):
    '''
    Create a new primitive element which is a merge of a
    rsc_template and a primitive which references it.
    '''
    dnode = etree.Element(prim_node.tag)
    merge_nodes(dnode, tmpl_node)
    merge_nodes(dnode, prim_node)
    # the resulting node should inherit all primitives attributes
    for a, v in list(prim_node.items()):
        dnode.set(a, v)
    # but class/provider/type are coming from the template
    # savannah#41410: stonith resources do not have the provider
    # attribute
    for a in ("class", "provider", "type"):
        v = tmpl_node.get(a)
        if v is not None:
            dnode.set(a, v)
    return dnode def remove_id_used_attributes(e):
    if e is not None:
        xmltraverse(e, remove_id_used_attr) def get_top_cib_nodes(node, nodes_l):
    '''
    All nodes which can be represented as CIB objects, but not
    nodes which are children of other CIB objects.
    '''
    for c in node.iterchildren():
        if is_cib_element(c):
            nodes_l.append(c)
        else:
            get_top_cib_nodes(c, nodes_l)
    return nodes_l def merge_attributes(dnode, snode, tag):
    rc = False
    add_children = []
    for sc in snode.iterchildren(tag):
        dc = lookup_node(sc, dnode, ignore_id=True)
        if dc is not None:
            for a, v in list(sc.items()):
                if a == "id":
                    continue
                if v != dc.get(a):
                    dc.set(a, v)
                    rc = True
        else:
            add_children.append(sc)
            rc = True
    for c in add_children:
        dnode.append(copy.deepcopy(c))
    return rc def is_cib_element(node):
    return node.tag in constants.cib_cli_map def sanity_check_meta(ident, node, attr_list):
    rc = 0
    if node is None or not attr_list:
        return rc
    for c in node.iterchildren():
        if c.tag == "meta_attributes":
            rc |= sanity_check_nvpairs(ident, c, attr_list)
    return rc def is_simpleconstraint(node):
    return len(node.xpath("resource_set/resource_ref")) == 0 def is_template(node):
    return node.tag == "template" def rmnode(e):
    if e is not None and e.getparent() is not None:
        e.getparent().remove(e) def is_defaults(node):
    return node.tag in constants.defaults_tags def is_live_cib():
    '''We working with the live cluster?'''
    return not get_cib_in_use() and not os.getenv("CIB_file") def get_rsc_operations(rsc_node):
    actions = [op2list(op) for op in rsc_node.xpath('.//operations/op')]
    actions = [[op, pl] for op, pl in actions if op]
    return actions def delete_rscref(c_obj, rsc_id):
    return delete_rscref_simple(c_obj, rsc_id) or \
        delete_rscref_rset(c_obj, rsc_id) def xml_equals(n, m, show=False):
    rc = xml_equals_unordered(n, m)
    if not rc and show and config.core.debug:
        # somewhat strange, but that's how this works
        from doctest import Example
        example = Example("etree.tostring(n)", xml_tostring(n))
        got = xml_tostring(m)
        print(_checker.output_difference(example, got, 0))
    return rc def lookup_node(node, oldnode, location_only=False, ignore_id=False):
    '''
    Find a child of oldnode which matches node.
    This is used to "harvest" existing ids in order to prevent
    irrelevant changes to the XML code.
    The list of attributes to match is in the dictionary
    match_list.
    The "id" attribute is treated differently. In case the new node
    (the first parameter here) contains the id, then the "id"
    attribute is added to the match list.
    '''
    if oldnode is None:
        return None
    attr_list = list(match_list[node.tag])
    if not ignore_id and node.get("id"):
        attr_list.append("id")
    for c in oldnode.iterchildren():
        if not location_only and is_id_used_attr(c):
            continue
        if node.tag == c.tag:
            for a in attr_list:
                if node.get(a) != c.get(a):
                    break
            else:
                return c
    return None class RscState(object):
    '''
    Get the resource status and some other relevant bits.
    In particular, this class should allow for a bit of caching
    of cibadmin -Q -o resources output in case we need to check
    more than one resource in a row.
    '''

    rsc_status = "crm_resource -W -r '%s'"

    def __init__(self):
        self.current_cib = None
        self.rsc_elem = None
        self.prop_elem = None
        self.rsc_dflt_elem = None

    def _init_cib(self):
        cib = cibdump2elem("configuration")
        self.current_cib = cib
        self.rsc_elem = get_first_conf_elem(cib, "resources")
        self.prop_elem = get_first_conf_elem(cib, "crm_config/cluster_property_set")
        self.rsc_dflt_elem = get_first_conf_elem(cib, "rsc_defaults/meta_attributes")

    def rsc2node(self, ident):
        '''
        Get a resource XML element given the id.
        NB: this is called from almost all other methods.
        Hence we initialize the cib here. CIB reading is
        expensive.
        '''
        if self.rsc_elem is None:
            self._init_cib()
        if self.rsc_elem is None:
            return None
        # does this need to be optimized?
        expr = './/*[@id="%s"]' % ident
        try:
            return self.rsc_elem.xpath(expr)[0]
        except (IndexError, AttributeError):
            return None

    def has_rsc_stickiness(self):
        """
        Check if resource-stickiness already set
        """
        self._init_cib()
        if self.rsc_dflt_elem is None:
            return False
        attr = get_attr_in_set(self.rsc_dflt_elem, "resource-stickiness")
        return attr is not None

    def is_ms_or_promotable_clone(self, ident):
        '''
        Test if the resource is master-slave.
        '''
        rsc_node = self.rsc2node(ident)
        if rsc_node is None:
            return False
        return is_ms_or_promotable_clone(rsc_node)

    def rsc_clone(self, ident):
        '''
        Return id of the clone/ms containing this resource
        or None if it's not cloned.
        '''
        rsc_node = self.rsc2node(ident)
        if rsc_node is None:
            return None
        pnode = rsc_node.getparent()
        if pnode is None:
            return None
        if is_group(pnode):
            pnode = pnode.getparent()
        if is_clonems(pnode):
            return pnode.get("id")
        return None

    def is_managed(self, ident):
        '''
        Is this resource managed?
        '''
        rsc_node = self.rsc2node(ident)
        if rsc_node is None:
            return False
        # maintenance-mode, if true, overrides all
        attr = get_attr_value(self.prop_elem, "maintenance-mode")
        if attr and is_xs_boolean_true(attr):
            return False
        # then check the rsc is-managed meta attribute
        rsc_meta_node = get_rsc_meta_node(rsc_node)
        attr = get_attr_value(rsc_meta_node, "is-managed")
        if attr:
            return is_xs_boolean_true(attr)
        # then rsc_defaults is-managed attribute
        attr = get_attr_value(self.rsc_dflt_elem, "is-managed")
        if attr:
            return is_xs_boolean_true(attr)
        # finally the is-managed-default property
        attr = get_attr_value(self.prop_elem, "is-managed-default")
        if attr:
            return is_xs_boolean_true(attr)
        return True

    def is_running(self, ident):
        '''
        Is this resource running?
        '''
        if not is_live_cib():
            return False
        test_id = self.rsc_clone(ident) or ident
        rc, outp = get_stdout(self.rsc_status % test_id, stderr_on=False)
        return outp.find("running") > 0 and outp.find("NOT") == -1

    def is_group(self, ident):
        '''
        Test if the resource is a group
        '''
        rsc_node = self.rsc2node(ident)
        if rsc_node is None:
            return False
        return is_group(rsc_node)

    def can_delete(self, ident):
        '''
        Can a resource be deleted?
        The order below is important!
        '''
        return not (self.is_running(ident) and not self.is_group(ident) and self.is_managed(ident)) def text2elem(text):
    """
    Convert a text format CIB to
    an XML tree.
    """
    try:
        return etree.fromstring(text)
    except Exception as err:
        logger_utils.text_xml_parse_err(err, text)
        return None def is_related(rsc_id, node):
    """
    checks if the given node is an element
    that has a direct relation to rsc_id. That is,
    if it contains it, if it references it...
    """
    if is_constraint(node) and rsc_constraint(rsc_id, node):
        return True
    if node.tag == 'tag':
        if len(node.xpath('.//obj_ref[@id="%s"]' % (rsc_id))) > 0:
            return True
        return False
    if is_container(node):
        for tag in ('primitive', 'group', 'clone', 'master'):
            if len(node.xpath('.//%s[@id="%s"]' % (tag, rsc_id))) > 0:
                return True
        return False
    return False def check_id_ref(elem, id_ref):
    target = elem.xpath('.//*[@id="%s"]' % (id_ref))
    if len(target) == 0:
        logger.error("Reference not found: %s", id_ref)
    elif len(target) > 1:
        logger.error("Ambiguous reference to %s", id_ref) def xml_tostring(*args, **kwargs):
    """
    Python 2/3 conversion utility:
    etree.tostring returns a bytestring, but
    we need actual Python strings.
    """
    return etree.tostring(*args, **kwargs).decode('utf-8') def sanitize_cib_for_patching(doc):
    """
    Custom version of sanitize_cib which
    doesn't sort container children, to use
    for processing the original CIB when
    generating a patch to apply using crm_diff.
    """
    xml_processnodes(doc, is_status_node, rmnodes)
    xml_processnodes(doc, is_entity, rmnodes)
    xml_processnodes(doc, true, remove_dflt_attrs)
    xml_processnodes(doc, true, remove_text) def get_score(node):
    score = node.get("score")
    if not score:
        score = node.get("score-attribute")
    else:
        if score.find("INFINITY") >= 0:
            score = score.replace("INFINITY", "inf")
    if not score:
        score = ""
    return score def nvpairs2list(node, add_id=False):
    '''
    Convert an attribute node to a list of nvpairs.
    Also converts an id-ref or id into plain nvpairs.
    The id attribute is normally skipped, since they tend to be
    long and therefore obscure the relevant content. For some
    elements, however, they are included (e.g. properties).
    '''
    ret = []
    if 'id-ref' in node:
        ret.append(xmlutil.nvpair('$id-ref', node.get('id-ref')))
    nvpairs = node.xpath('./nvpair | ./attributes/nvpair')
    if 'id' in node and (add_id or len(nvpairs) == 0):
        ret.append(xmlutil.nvpair('$id', node.get('id')))
    ret.extend(nvpairs)
    return ret def abs_pos_score(score):
    return score in ("inf", "+inf", "Mandatory") def cli_acl_roleref(node, format_mode=1):
    return "%s:%s" % (clidisplay.keyword("role"),
                      clidisplay.attr_value(node.get("id"))) def nvpair_format(n, v):
    if v is None:
        return clidisplay.attr_name(n)
    else:
        return '='.join((clidisplay.attr_name(n),
                         clidisplay.attr_value(quote_wrap(v)))) def cli_nvpair(nvp):
    'Converts an nvpair tag or a (name, value) pair to CLI syntax'
    from .cibconfig import cib_factory
    from .utils import obscured
    nodeid = nvp.get('id')
    idref = nvp.get('id-ref')
    name = nvp.get('name')
    value = nvp.get('value')
    value = obscured(name, value)
    if idref is not None:
        if name is not None:
            return '@%s:%s' % (idref, name)
        return '@%s' % (idref)
    elif nodeid is not None and cib_factory.is_id_refd(nvp.tag, nodeid):
        return '$%s:%s' % (nodeid, nvpair_format(name, value))
    return nvpair_format(name, value) def cli_acl_rule(node, format_mode=1):
    l = []
    acl_rule_name = node.tag
    l.append(clidisplay.keyword(acl_rule_name))
    for xml_spec in constants.acl_spec_map:
        v = node.get(xml_spec)
        if v:
            l.append(acl_spec_format(xml_spec, v))
    return ' '.join(l) def rsc_set_constraint(node, obj_type):
    col = []
    cnt = 0
    for n in node.findall("resource_set"):
        sequential = boolean_maybe(n.get("sequential"))
        require_all = boolean_maybe(n.get("require-all"))
        if require_all is False:
            col.append("[")
        elif sequential is False:
            col.append("(")
        role = n.get("role")
        action = n.get("action")
        for r in n.findall("resource_ref"):
            rsc = clidisplay.rscref(r.get("id"))
            q = (obj_type == "order") and action or role
            col.append(q and "%s:%s" % (rsc, q) or rsc)
            cnt += 1
        if require_all is False:
            if sequential in (None, True):
                col.append(nvpair_format('sequential', 'true'))
            col.append("]")
        elif sequential is False:
            if require_all is False:
                col.append(nvpair_format('require-all', 'false'))
            col.append(")")
    is_ticket = obj_type == 'rsc_ticket'
    is_location = obj_type == 'location'
    is_seq_all = sequential in (None, True) and require_all in (None, True)
    if not is_location and ((is_seq_all and not is_ticket and cnt <= 2) or
                            (is_ticket and cnt <= 1)):  # a degenerate thingie
        col.insert(0, "_rsc_set_")
    return col def get_kind(node):
    kind = node.get("kind")
    if not kind:
        kind = ""
    return kind def head_id_format(nodeid):
    "Special format for property list / node id"
    if utils.noquotes(nodeid):
        return "%s:" % (clidisplay.ident(nodeid))
    return '%s="%s"' % (clidisplay.ident('$id'),
                        clidisplay.attr_value(nodeid)) def simple_rsc_constraint(node, obj_type):
    col = []
    if obj_type == "colocation":
        col.append(mkrscrole(node, "rsc"))
        col.append(mkrscrole(node, "with-rsc"))
    elif obj_type == "order":
        col.append(mkrscaction(node, "first"))
        col.append(mkrscaction(node, "then"))
    else:  # rsc_ticket
        col.append(mkrscrole(node, "rsc"))
    return col def cli_rule(node):
    from .cibconfig import cib_factory
    s = []
    node_id = node.get("id")
    if node_id and cib_factory.is_id_refd(node.tag, node_id):
        s.append(nvpair_format('$id', node_id))
    else:
        idref = node.get("id-ref")
        if idref:
            return nvpair_format('$id-ref', idref)
    rsc_role = node.get("role")
    if rsc_role:
        s.append(nvpair_format('$role', rsc_role))
    score = cli_rule_score(node)
    if score:
        s.append("%s:" % (clidisplay.score(score)))
    s.append(cli_exprs(node))
    return ' '.join(s) def cli_format(pl, break_lines=True, xml=False):
    if break_lines and xml:
        return ' \\\n'.join(pl)
    elif break_lines:
        return ' \\\n\t'.join(pl)
    else:
        return ' '.join(pl) def cli_acl_role(node):
    return clidisplay.attr_value(node.get("id")) def cli_acl_permission(node):
    s = [clidisplay.keyword(node.get('kind'))]
    # if node.get('id'):
    #     s.append(head_id_format(node.get('id')))
    if node.get('description'):
        s.append(nvpair_format('description', node.get('description')))
    for attrname, cliname in constants.acl_spec_map_2_rev:
        if attrname in node.attrib:
            s.append(cli_acl_spec2_format(cliname, node.get(attrname)))
    return ' '.join(s) def cli_path(p):
    return clidisplay.attr_value(quote_wrap(p))
import copy
import os
import sys
import re
import fnmatch
import time
import collections
        import urllib.request
        import urllib.error
        import urllib.parse
from lxml import etree
from . import config
from . import options
from . import constants
from . import tmpfiles
from . import clidisplay
from . import idmgmt
from . import schema
from . import utils
from . import cibverify
from . import parse
from . import ordereddict
from . import orderedset
from . import cibstatus
from . import crm_gv
from . import ui_utils
from . import userdir
from .ra import get_ra, get_properties_list, get_pe_meta, get_properties_meta
from .utils import ext_cmd, safe_open_w, pipe_string, safe_close_w, crm_msec
from .utils import ask, lines2cli, olist
from .utils import page_string, cibadmin_can_patch, str2tmp, ensure_sudo_readable
from .utils import run_ptest, is_id_valid, edit_file, get_boolean, filter_string
from .xmlutil import is_child_rsc, rsc_constraint, sanitize_cib, rename_id, get_interesting_nodes
from .xmlutil import is_pref_location, get_topnode, new_cib, get_rscop_defaults_meta_node
from .xmlutil import rename_rscref, is_ms_or_promotable_clone, silly_constraint, is_container, fix_comments
from .xmlutil import sanity_check_nvpairs, merge_nodes, op2list, mk_rsc_type, is_resource
from .xmlutil import stuff_comments, is_comment, is_constraint, read_cib, processing_sort_cli
from .xmlutil import find_operation, get_rsc_children_ids, is_primitive, referenced_resources
from .xmlutil import cibdump2elem, processing_sort, get_rsc_ref_ids, merge_tmpl_into_prim
from .xmlutil import remove_id_used_attributes, get_top_cib_nodes
from .xmlutil import merge_attributes, is_cib_element, sanity_check_meta
from .xmlutil import is_simpleconstraint, is_template, rmnode, is_defaults, is_live_cib
from .xmlutil import get_rsc_operations, delete_rscref, xml_equals, lookup_node, RscState
from .xmlutil import text2elem, is_related, check_id_ref, xml_tostring
from .xmlutil import sanitize_cib_for_patching
from .cliformat import get_score, nvpairs2list, abs_pos_score, cli_acl_roleref, nvpair_format
from .cliformat import cli_nvpair, cli_acl_rule, rsc_set_constraint, get_kind, head_id_format
from .cliformat import simple_rsc_constraint, cli_rule, cli_format
from .cliformat import cli_acl_role, cli_acl_permission, cli_path
from . import log
        from .utils import obscured
        self.cib_objects.remove(obj)
        for tag in self.related_tags(obj):
            # remove self from tag
            # remove tag if self is last tagged object in tag
            selfies = [x for x in tag.node.iterchildren() if x.get('id') == obj.obj_id]
            for c in selfies:
                rmnode(c)
            if not tag.node.xpath('./obj_ref'):
                self._remove_obj(tag)
                if not self._no_constraint_rm_msg:
                    logger.info("hanging %s deleted", str(tag))
        for c_obj in self.related_constraints(obj):
            if is_simpleconstraint(c_obj.node) and obj.children:
                # the first child inherits constraints
                rename_rscref(c_obj, obj.obj_id, obj.children[0].obj_id)
            deleted = False
            if delete_rscref(c_obj, obj.obj_id):
                deleted = True
            if silly_constraint(c_obj.node, obj.obj_id):
                # remove invalid constraints
                self._remove_obj(c_obj)
                if not self._no_constraint_rm_msg:
                    logger.info("hanging %s deleted", str(c_obj))
            elif deleted:
                logger.info("constraint %s updated", str(c_obj))

    def related_tags(self, obj):
        def related_tag(tobj):
            if tobj.obj_type != 'tag':
                return False
            for c in tobj.node.iterchildren():
                if c.get('id') == obj.obj_id:
                    return True
            return False
        return [x for x in self.cib_objects if related_tag(x)]

    def related_constraints(self, obj):
        def related_constraint(obj2):
            return is_constraint(obj2.node) and rsc_constraint(obj.obj_id, obj2.node)
        if not is_resource(obj.node):
            return []
        return [x for x in self.cib_objects if related_constraint(x)]

    def related_elements(self, obj):
        "Both constraints, groups, tags, ..."
        if not is_resource(obj.node):
            return []
        return [x for x in self.cib_objects if is_related(obj.obj_id, x.node)]

    def _redirect_children_constraints(self, obj):
        '''
        Redirect constraints to the new parent
        '''
        for child in obj.children:
            for c_obj in self.related_constraints(child):
                rename_rscref(c_obj, child.obj_id, obj.obj_id)
        # drop useless constraints which may have been created above
        for c_obj in self.related_constraints(obj):
            if silly_constraint(c_obj.node, obj.obj_id):
                self._no_constraint_rm_msg = True
                self._remove_obj(c_obj)
                self._no_constraint_rm_msg = False

    def template_primitives(self, obj):
        if not is_template(obj.node):
            return []
        c_list = []
        for obj2 in self.cib_objects:
            if not is_primitive(obj2.node):
                continue
            if obj2.node.get("template") == obj.obj_id:
                c_list.append(obj2)
        return c_list

    def _check_running_primitives(self, prim_l):
        rscstat = RscState()
        for prim in prim_l:
            if not rscstat.can_delete(prim.obj_id):
                logger.error("resource %s is running, can't delete it", prim.obj_id)
                return False
        return True

    def _add_to_remove_queue(self, obj):
        if obj.origin == "cib":
            self.remove_queue.append(obj)

    def _delete_1(self, obj):
        '''
        Remove an object and its parent in case the object is the
        only child.
        '''
        if obj.parent and len(obj.parent.children) == 1:
            self._delete_1(obj.parent)
        if obj in self.cib_objects:  # don't remove parents twice
            self._remove_obj(obj)

    def delete(self, *args):
        'Delete a cib object.'
        if not self.is_cib_sane():
            return False
        rc = True
        l = []
        rscstat = RscState()
        for obj_id in args:
            obj = self.find_object(obj_id)
            if not obj:
                # If --force is set:
                # Unless something more serious goes wrong here,
                # don't return an error code if the object
                # to remove doesn't exist. This should help scripted
                # workflows without compromising an interactive
                # use.
                if not config.core.force:
                    logger_utils.no_object_err(obj_id)
                    rc = False
                continue
            if not rscstat.can_delete(obj_id):
                logger.error("resource %s is running, can't delete it", obj_id)
                rc = False
                continue

            if is_template(obj.node):