Exemple #1
0
def Main():
    # TODO: can_process_remote should be suppressed because it duplicates CanProcessRemote
    cgiEnv = lib_common.CgiEnv(can_process_remote=True)
    pid = int(cgiEnv.GetId())
    machine_name = cgiEnv.GetHost()

    grph = cgiEnv.GetGraph()

    cimom_url = lib_wbem.HostnameToWbemServer(machine_name)

    DEBUG(
        "wbem_process_info.py currentHostname=%s pid=%d machine_name=%s cimom_url=%s",
        lib_util.currentHostname, pid, machine_name, cimom_url)

    conn_wbem = lib_wbem.WbemConnection(cimom_url)

    name_space = "root/cimv2"
    try:
        inst_lists = conn_wbem.ExecQuery(
            "WQL", 'select * from CIM_Process  where Handle="%s"' % pid,
            name_space)
    except:
        lib_common.ErrorMessageHtml("Error:" + str(sys.exc_info()))

    class_name = "CIM_Process"
    dict_props = {"Handle": pid}

    root_node = lib_util.EntityClassNode(class_name, name_space, cimom_url,
                                         "WBEM")

    # There should be only one object, hopefully.
    for an_inst in inst_lists:
        dict_inst = dict(an_inst)

        host_only = lib_util.EntHostToIp(cimom_url)
        if lib_util.IsLocalAddress(host_only):
            uri_inst = lib_common.gUriGen.UriMakeFromDict(
                class_name, dict_props)
        else:
            uri_inst = lib_common.RemoteBox(host_only).UriMakeFromDict(
                class_name, dict_props)

        grph.add((root_node, lib_common.MakeProp(class_name), uri_inst))

        url_namespace = lib_wbem.NamespaceUrl(name_space, cimom_url,
                                              class_name)
        nod_namespace = lib_common.NodeUrl(url_namespace)
        grph.add((root_node, pc.property_cim_subnamespace, nod_namespace))

        # None properties are not printed.
        for iname_key in dict_inst:
            iname_val = dict_inst[iname_key]
            # TODO: If this is a reference, create a Node !!!!!!!
            if not iname_val is None:
                grph.add((uri_inst, lib_common.MakeProp(iname_key),
                          lib_common.NodeLiteral(iname_val)))

        # TODO: Call the method Associators(). Idem References().

    cgiEnv.OutCgiRdf()
Exemple #2
0
def Main():
    cgiEnv = lib_common.ScriptEnvironment(can_process_remote=True)

    cimom_url = cgiEnv.GetHost()

    grph = cgiEnv.GetGraph()

    # There is no consensus on the WBEM class for namespaces,
    # so we have ours which must be correctly mapped.
    namespace_class = "wbem_namespace"
    root_node = lib_util.EntityUri(namespace_class, "")

    try:
        conn_wbem = lib_wbem.WbemConnection(cimom_url)
        nsd = lib_wbem.EnumNamespacesCapabilities(conn_wbem)
    except Exception as exc:
        lib_common.ErrorMessageHtml("Namespaces from :" + cimom_url +
                                    " Caught:" + str(exc))

    # TODO: We should draw a namespaces tree but more examples needed.
    for nskey in nsd:

        cnt = nsd[nskey]
        wbem_url = lib_wbem.NamespaceUrl(nskey, cimom_url)
        wbem_node = lib_common.NodeUrl(wbem_url)

        grph.add((root_node, pc.property_cim_subnamespace, wbem_node))
        grph.add(
            (wbem_node, pc.property_information, lib_util.NodeLiteral(nskey)))
        grph.add(
            (wbem_node, pc.property_information, lib_util.NodeLiteral(cnt)))

    cgiEnv.OutCgiRdf("LAYOUT_RECT")
Exemple #3
0
    def test_remote_ontology(self):
        """Very slow test: It displays the entire list of classes and their properties."""
        # In contrast to another test which remotely connect to a Survol agent,
        # which then makes a local TCP/IP connection to its local WBEM Cimom,
        # this test directly connects to the remote Cimom.
        wbem_connection = lib_wbem.WbemConnection(SurvolWbemCimom)

        map_classes, map_attributes = lib_wbem.ExtractRemoteWbemOntology(
            wbem_connection)
        self.assertTrue("CIM_Process" in map_classes)
        self.assertTrue("Handle" in map_attributes)
Exemple #4
0
def _create_wbem_node(grph, root_node, entity_host, name_space, class_name,
                      entity_id):
    wbem_namespace = name_space.replace("\\", "/")
    wbem_servers_desc_list = lib_wbem.GetWbemUrls(entity_host, wbem_namespace,
                                                  class_name, entity_id)

    # If there are no servers.
    pair_name_node = None

    for url_server in wbem_servers_desc_list:
        wbem_node = lib_common.NodeUrl(url_server[0])
        grph.add((root_node, pc.property_wbem_data, wbem_node))

        wbemHostNode = lib_uris.gUriGen.HostnameUri(url_server[1])
        grph.add((wbem_node, pc.property_host, wbemHostNode))

        # TODO: Add a Yawn server ??
        grph.add((wbem_node, pc.property_wbem_server,
                  lib_util.NodeLiteral(url_server[1])))

        # Now adds the description of the class.
        try:
            conn_wbem = lib_wbem.WbemConnection(entity_host)
        except Exception as exc:
            logging.error("WbemConnection throw:%s" % str(exc))
            continue

        kla_descrip = lib_wbem.WbemClassDescription(conn_wbem, class_name,
                                                    wbem_namespace)
        ok_wbem_class = True
        if not kla_descrip:
            ok_wbem_class = False
            kla_descrip = "Undefined class %s %s" % (wbem_namespace,
                                                     class_name)
        grph.add((wbem_node, pc.property_information,
                  lib_util.NodeLiteral(kla_descrip)))

        # Maybe this class is not Known in WBEM.
        try:
            pair_name_node = _wbem_add_all_base_classes(
                grph, conn_wbem, wbem_node, entity_host, name_space,
                class_name)
        except:
            pair_name_node = None

        if ok_wbem_class and wbem_ok and name_space != "" and entity_host != "":
            namespace_url = lib_wbem.NamespaceUrl(name_space, entity_host,
                                                  class_name)
            namespace_node = lib_common.NodeUrl(namespace_url)
            grph.add((wbem_node, pc.property_information, namespace_node))

    # TODO: This is a bit absurd because we return just one list.
    return pair_name_node
Exemple #5
0
def CreateWbemNode(grph, rootNode, entity_host, nameSpace, className,
                   entity_id):
    wbemNamespace = nameSpace.replace("\\", "/")
    wbem_servers_desc_list = lib_wbem.GetWbemUrls(entity_host, wbemNamespace,
                                                  className, entity_id)

    # If there are no servers.
    pairNameNode = None

    for url_server in wbem_servers_desc_list:
        wbemNode = lib_common.NodeUrl(url_server[0])
        grph.add((rootNode, pc.property_wbem_data, wbemNode))

        # Le naming est idiot: "rchateau-HP at localhost"
        wbemHostNode = lib_common.gUriGen.HostnameUri(url_server[1])
        grph.add((wbemNode, pc.property_host, wbemHostNode))

        # TODO: Add a Yawn server ??
        grph.add((wbemNode, pc.property_wbem_server,
                  lib_common.NodeLiteral(url_server[1])))

        # Now adds the description of the class.
        connWbem = lib_wbem.WbemConnection(entity_host)
        klaDescrip = lib_wbem.WbemClassDescription(connWbem, className,
                                                   wbemNamespace)
        okWbemClass = True
        if not klaDescrip:
            okWbemClass = False
            klaDescrip = "Undefined class %s %s" % (wbemNamespace, className)
        grph.add((wbemNode, pc.property_information,
                  lib_common.NodeLiteral(klaDescrip)))

        # Maybe this class is not Known in WBEM.
        try:
            pairNameNode = WbemAddBaseClasses(grph, connWbem, wbemNode,
                                              entity_host, nameSpace,
                                              className)
        except:
            pairNameNode = None

        if okWbemClass and wbemOk and nameSpace != "" and entity_host != "":
            namespaceUrl = lib_wbem.NamespaceUrl(nameSpace, entity_host,
                                                 className)
            namespaceNode = lib_common.NodeUrl(namespaceUrl)
            grph.add((wbemNode, pc.property_information, namespaceNode))

    # TODO: This is a bit absurd because we return just one list.
    return pairNameNode
def Main():
    cgiEnv = lib_common.CgiEnv(can_process_remote=True)

    cimomUrl = cgiEnv.GetHost()

    grph = cgiEnv.GetGraph()

    # There is no consensus on the WBEM class for namespaces,
    # so we have ours which must be correctly mapped.
    namespace_class = "wbem_namespace"
    rootNode = lib_util.EntityUri(namespace_class, "")

    connWbem = lib_wbem.WbemConnection(cimomUrl)

    try:
        nsd = lib_wbem.EnumNamespacesCapabilities(connWbem)
    except Exception:
        exc = sys.exc_info()[1]
        lib_common.ErrorMessageHtml("Namespaces from :" + cimomUrl +
                                    " Caught:" + str(exc))

    # TODO: We should draw a namespaces tree but more examples needed.
    for nskey in nsd:

        cnt = nsd[nskey]
        # Special case because it is not displayed like a normal entity.
        # Oui mais ca marche aussi avec wmi ?
        # Pourrait-on combiner namespace+classe ? entity_type="root/cim_v2/CIM_Process" ?
        # Si l'entity_type termine par un slash, donc c'est un namespace ?
        # Ca nous permettrait de creer des namespaces dans notre ontologie,
        # par exemple pour Oracle. Ce serait simplement un directory.
        # ATTENTION: Avoir la liste de nos entity_types sera moins immediat.
        wbemUrl = lib_wbem.NamespaceUrl(nskey, cimomUrl)
        wbemNode = lib_common.NodeUrl(wbemUrl)

        grph.add((rootNode, pc.property_cim_subnamespace, wbemNode))
        grph.add(
            (wbemNode, pc.property_information, lib_common.NodeLiteral(nskey)))
        grph.add(
            (wbemNode, pc.property_information, lib_common.NodeLiteral(cnt)))

    cgiEnv.OutCgiRdf("LAYOUT_RECT")
Exemple #7
0
 def test_remote_namespaces(self):
     """At least the defaultnamespace must be there."""
     wbem_connection = lib_wbem.WbemConnection(SurvolWbemCimom)
     namespaces_dict = lib_wbem.EnumNamespacesCapabilities(wbem_connection)
     self.assertTrue("root/cimv2" in namespaces_dict)
Exemple #8
0
def Main():
    paramkeyMaxDepth = "Maximum depth"
    paramkeyYawnUrls = "Yawn urls"

    # TODO: The type should really be an integer.
    cgiEnv = lib_common.CgiEnv(can_process_remote=True,
                               parameters={
                                   paramkeyMaxDepth: 2,
                                   paramkeyYawnUrls: False
                               })

    wbemNamespace, entity_type = cgiEnv.get_namespace_type()

    maxDepth = int(cgiEnv.get_parameters(paramkeyMaxDepth))
    withYawnUrls = int(cgiEnv.get_parameters(paramkeyYawnUrls))

    DEBUG("wbemNamespace=%s entity_type=%s maxDepth=%d", wbemNamespace,
          entity_type, maxDepth)

    cimomUrl = cgiEnv.GetHost()

    if str(wbemNamespace) == "":
        lib_common.ErrorMessageHtml("namespace should not be empty.")

    grph = cgiEnv.GetGraph()

    connWbem = lib_wbem.WbemConnection(cimomUrl)

    # entity_type might an empty string.
    rootNode = WbemNamespaceNode(wbemNamespace, cimomUrl, entity_type)

    DEBUG("objtypes_wmi.py cimomUrl=%s entity_type=%s", cimomUrl, entity_type)

    treeClassesFiltered = lib_wbem.GetClassesTreeInstrumented(
        connWbem, wbemNamespace)

    PrintClassRecu(grph, rootNode, treeClassesFiltered, entity_type, 0,
                   wbemNamespace, cimomUrl, maxDepth, withYawnUrls)

    DEBUG("entity_type=%s", entity_type)

    # If we are not at the top of the tree:
    if entity_type != "":
        # Now, adds the base classes of this one, at least one one level.
        wbemKlass = lib_wbem.WbemGetClassObj(connWbem, entity_type,
                                             wbemNamespace)
        if wbemKlass:
            superKlassName = wbemKlass.superclass

            DEBUG("superKlassName=%s", superKlassName)
            # An empty string or None.
            if superKlassName:
                wbemSuperNode = WbemNamespaceNode(wbemNamespace, cimomUrl,
                                                  superKlassName)
                grph.add((wbemSuperNode, pc.property_cim_subclass, rootNode))
                klaDescrip = lib_wbem.WbemClassDescription(
                    connWbem, superKlassName, wbemNamespace)
                if not klaDescrip:
                    klaDescrip = "Undefined class %s %s" % (wbemNamespace,
                                                            superKlassName)
                grph.add((wbemSuperNode, pc.property_information,
                          lib_common.NodeLiteral(klaDescrip)))

    cgiEnv.OutCgiRdf("LAYOUT_RECT_TB", [pc.property_cim_subclass])
Exemple #9
0
def Main():

    cgiEnv = lib_common.ScriptEnvironment(can_process_remote=True)

    entity_id = cgiEnv.GetId()
    logging.debug("entity_id=%s", entity_id)
    if entity_id == "":
        lib_common.ErrorMessageHtml("No entity_id")

    # Just the path, shorter than cgiEnv.get_parameters("xid")
    cimom_url = cgiEnv.GetHost()

    name_space, class_name = cgiEnv.get_namespace_type()
    logging.debug("cimom_url=%s name_space=%s class_name=%s", cimom_url,
                  name_space, class_name)

    if name_space == "":
        name_space = "root/cimv2"
        logging.info("Setting namespace to default value.")

    if class_name == "":
        lib_common.ErrorMessageHtml("No class name. entity_id=%s" % entity_id)

    grph = cgiEnv.GetGraph()

    try:
        conn = lib_wbem.WbemConnection(cimom_url)
    except Exception as exc:
        lib_common.ErrorMessageHtml("Connecting to :" + cimom_url +
                                    " Caught:" + str(exc))

    root_node = lib_util.EntityClassNode(class_name, name_space, cimom_url,
                                         "WBEM")
    kla_descrip = lib_wbem.WbemClassDescription(conn, class_name, name_space)
    if not kla_descrip:
        kla_descrip = "Undefined class %s %s" % (name_space, class_name)
    grph.add((root_node, pc.property_information,
              lib_util.NodeLiteral(kla_descrip)))

    split_monik = cgiEnv.m_entity_id_dict

    logging.debug("entity_wbem.py name_space=%s class_name=%s cimom_url=%s",
                  name_space, class_name, cimom_url)

    # This works:
    # conn = pywbem.WBEMConnection("http://192.168.0.17:5988",("pegasus","toto"))
    # conn.ExecQuery("WQL","select * from CIM_System","root/cimv2")
    # conn.ExecQuery("WQL",'select * from CIM_Process  where Handle="4125"',"root/cimv2")
    #
    # select * from CIM_Directory or CIM_DataFile does not return anything.

    inst_lists = WbemPlainExecQuery(conn, class_name, split_monik, name_space)
    logging.debug("inst_lists=%s", str(inst_lists))
    if inst_lists is None:
        inst_lists = WbemNoQueryOneInst(conn, class_name, split_monik,
                                        name_space)
        if inst_lists is None:
            inst_lists = WbemNoQueryFilterInstances(conn, class_name,
                                                    split_monik, name_space)

    # TODO: Some objects are duplicated.
    # 'CSCreationClassName'   CIM_UnitaryComputerSystem Linux_ComputerSystem
    # 'CreationClassName'     PG_UnixProcess            TUT_UnixProcess
    num_insts = len(inst_lists)

    # If there are duplicates, adds a property which we hope is different.
    prop_discrim = "CreationClassName"

    # TODO!! WHAT OF THIS IS NOT THE RIGHT ORDER ???
    # Remove the double-quotes around the argument. WHAT IF THEY ARE NOT THERE ??

    for an_inst in inst_lists:

        # TODO: Use the right accessor for better performance.
        # On peut peut etre mettre tout ca dans une fonction sauf l execution de la query.
        dict_inst = dict(an_inst)

        # This differentiates several instance with the same properties.
        if num_insts > 1:
            # TODO: Should check if this property is different for all instances !!!
            with_extra_args = {prop_discrim: dict_inst[prop_discrim]}
            all_args = split_monik.copy()
            all_args.update(with_extra_args)
            dict_props = all_args
        else:
            dict_props = split_monik

        host_only = lib_util.EntHostToIp(cimom_url)
        uri_inst = lib_common.MachineBox(host_only).node_from_dict(
            class_name, dict_props)

        grph.add((root_node, lib_common.MakeProp(class_name), uri_inst))

        AddNamespaceLink(grph, root_node, name_space, cimom_url, class_name)

        # None properties are not printed.
        for iname_key in dict_inst:
            # Do not print twice values which are in the name.
            if iname_key in split_monik:
                continue
            iname_val = dict_inst[iname_key]
            # TODO: If this is a reference, create a Node !!!!!!!
            if not iname_val is None:
                grph.add((uri_inst, lib_common.MakeProp(iname_key),
                          lib_util.NodeLiteral(iname_val)))

        # TODO: Should call Associators(). Same for References().

    cgiEnv.OutCgiRdf()
def Main():

    # TODO: The type should really be an integer.
    cgiEnv = lib_common.CgiEnv(can_process_remote=True)

    # cimomUrl = cgiEnv.GetHost()
    # http://192.168.1.88
    machineName = cgiEnv.GetId()

    grph = cgiEnv.GetGraph()

    cimomUrl = lib_wbem.HostnameToWbemServer(machineName)

    sys.stderr.write("wbem_hostname_processes.py cimomUrl=%s\n" % cimomUrl)

    # If running on the local machine, pass the host as None otherwise authorization is checked
    # just like a remote machine, which means User Account Control (UAC) disabling,
    # and maybe setting LocalAccountTokenFilterPolicy=1
    if lib_util.IsLocalAddress(machineName):
        machName_or_None = None
        serverBox = lib_common.gUriGen
    else:
        machName_or_None = machineName
        serverBox = lib_common.RemoteBox(machineName)

    # >>> conn = pywbem.WBEMConnection("http://192.168.1.88:5988" , ('pe***us','t*t*') )
    connWbem = lib_wbem.WbemConnection(cimomUrl)

    try:
        lstProc = connWbem.EnumerateInstances(ClassName="PG_UnixProcess",
                                              namespace="root/cimv2")
    except:
        lib_common.ErrorMessageHtml("Error:" + str(sys.exc_info()))

    # We should be using the class CMI_Process instead of PG_UnixProcess but it returns the error:
    # Python 2.7, pywbem.__version__ '0.8.0-dev'
    # >>> conn = pywbem.WBEMConnection("https://192.168.1.88:5989" , ('my-user','my-pass') )
    # >>> lst = conn.EnumerateInstanceNames(ClassName="CIM_Process",namespace="root/cimv2")
    # ...pywbem.cim_operations.CIMError: (1, u'CIM_ERR_FAILED: Error initializing CMPI MI /home/rchateau/TestProviderOpenLMI/tutorial_final/T
    # UT_UnixProcess.py, the following MI factory function(s) returned an error: _Generic_Create_InstanceMI, message was: cmpi:Traceback (
    # most recent call last):<br>  File "/usr/lib64/python2.7/site-packages/cmpi_pywbem_bindings.py", line 34, in <module><br>    from pyw
    # bem.cim_provider2 import ProviderProxy<br>ImportError: No module named cim_provider2<br>')

    # >>> lstProc[3].keys()
    # [u'OSCreationClassName', u'UserModeTime', u'Parameters', u'ExecutionState', u'ProcessGroupID', u'Priority', u'OtherExecutionDescript
    # ion', u'Handle', u'Description', u'RealUserID', u'CSCreationClassName', u'ProcessTTY', u'OSName', u'ProcessSessionID', u'CreationCla
    # ssName', u'WorkingSetSize', u'Name', u'CSName', u'ParentProcessID', u'KernelModeTime', u'Caption', u'ProcessNiceValue']

    # With a dictionary so node are created once only.
    Main.dictWbemPidToNode = {}

    def WbemPidToNode(procId):
        sys.stderr.write("procId=%s\n" % procId)
        try:
            return Main.dictWbemPidToNode[procId]
        except KeyError:
            node = serverBox.PidUri(procId)

            Main.dictWbemPidToNode[procId] = node
            return node

    for oneProc in lstProc:
        node_process = WbemPidToNode(oneProc["Handle"])
        parent_node_process = WbemPidToNode(oneProc["ParentProcessID"])

        grph.add((node_process, pc.property_ppid, parent_node_process))

        grph.add((node_process, pc.property_information,
                  lib_common.NodeLiteral(oneProc["Caption"])))

        if False:
            if oneProc["Caption"] != oneProc["Description"]:
                grph.add((node_process, lib_common.MakeProp("Description"),
                          lib_common.NodeLiteral(oneProc["Description"])))

            for prpNam in [
                    "WorkingSetSize", "KernelModeTime", "ProcessNiceValue",
                    "OtherExecutionDescription"
            ]:
                try:
                    grph.add((node_process, lib_common.MakeProp(prpNam),
                              lib_common.NodeLiteral(oneProc["prpNam"])))
                except KeyError:
                    pass

    cgiEnv.OutCgiRdf()
Exemple #11
0
cimomUrl = cgiEnv.GetHost()

(nameSpace, className, entity_namespace_type) = cgiEnv.GetNamespaceType()
sys.stderr.write("entity_wbem.py cimomUrl=%s nameSpace=%s className=%s\n" %
                 (cimomUrl, nameSpace, className))

if nameSpace == "":
    nameSpace = "root/cimv2"
    sys.stderr.write("Setting namespace to default value\n")

if className == "":
    lib_common.ErrorMessageHtml("No class name. entity_id=%s" % entity_id)

grph = cgiEnv.GetGraph()

conn = lib_wbem.WbemConnection(cimomUrl)

rootNode = lib_util.EntityClassNode(className, nameSpace, cimomUrl, "WBEM")
klaDescrip = lib_wbem.WbemClassDescription(conn, className, nameSpace)
if not klaDescrip:
    klaDescrip = "Undefined class %s %s" % (nameSpace, className)
grph.add(
    (rootNode, pc.property_information, lib_common.NodeLiteral(klaDescrip)))

splitMonik = lib_util.SplitMoniker(cgiEnv.m_entity_id)

sys.stderr.write("entity_wbem.py nameSpace=%s className=%s cimomUrl=%s\n" %
                 (nameSpace, className, cimomUrl))

# This works:
# conn = pywbem.WBEMConnection("http://192.168.0.17:5988",("pegasus","toto"))
Exemple #12
0
def Main():
    paramkeyMaxInstances = "Max instances"
    paramkeyStartIndex = "Start index"

    # This can process remote hosts because it does not call any script, just shows them.
    cgiEnv = lib_common.CgiEnv(can_process_remote=True,
                               parameters={
                                   paramkeyMaxInstances: 80,
                                   paramkeyStartIndex: 0
                               })

    maxInstances = cgiEnv.get_parameters(paramkeyMaxInstances)
    startIndex = cgiEnv.get_parameters(paramkeyStartIndex)

    grph = cgiEnv.GetGraph()

    nameSpace, className = cgiEnv.get_namespace_type()
    DEBUG("nameSpace=%s className=%s", nameSpace, className)

    entity_host = cgiEnv.GetHost()

    rootNode = lib_util.EntityClassNode(className, nameSpace, entity_host,
                                        "WBEM")

    # Hard-coded default namespace.
    if nameSpace == "":
        nameSpace = "root/CIMV2"

    # This adds a link to the namespace of this WBEM class: It shows its inheritance graph.
    urlNamespace = lib_wbem.NamespaceUrl(nameSpace, entity_host, className)
    nodNamespace = lib_common.NodeUrl(urlNamespace)
    grph.add((rootNode, pc.property_cim_subnamespace, nodNamespace))

    try:
        connWbem = lib_wbem.WbemConnection(entity_host)
        wbemKlass = connWbem.GetClass(className,
                                      namespace=nameSpace,
                                      LocalOnly=False,
                                      IncludeQualifiers=True)
    except Exception:
        exc = sys.exc_info()[1]
        lib_common.ErrorMessageHtml("EnumerateInstanceNames: entity_host=" +
                                    entity_host + " nameSpace=" + nameSpace +
                                    " className=" + className + ". Caught:" +
                                    str(exc))

    klaDescrip = lib_wbem.WbemClassDescrFromClass(wbemKlass)
    grph.add((rootNode, pc.property_information,
              lib_common.NodeLiteral("WBEM description: " + klaDescrip)))

    # Pour afficher du texte: Remplacer le help statique.
    # offset va etre un parametre. Helas ne pas se fairew d illusions sur "offset"

    # WBEM and WMI both have the annoying limitation that it is not possible to select only a range of instances.
    try:
        inst_names = connWbem.EnumerateInstanceNames(ClassName=className,
                                                     namespace=nameSpace)
    except Exception:
        exc = sys.exc_info()[1]
        lib_common.ErrorMessageHtml("EnumerateInstanceNames: entity_host=" +
                                    entity_host + " nameSpace=" + nameSpace +
                                    " className=" + className + ". Caught:" +
                                    str(exc))

    try:
        isAssociation = wbemKlass.qualifiers['Association'].value
    except KeyError:
        isAssociation = False

    # It is possible to display an association like a normal class but it is useless.
    if isAssociation:
        if True:
            DisplayAssociatorsAsNetwork(grph, inst_names, rootNode, nameSpace,
                                        entity_host, maxInstances, startIndex)
        else:
            DisplayAssociatorsAsList(grph, inst_names, rootNode, nameSpace,
                                     entity_host, className, maxInstances,
                                     startIndex)
    else:
        DisplayPlainClass(grph, inst_names, rootNode, nameSpace, entity_host,
                          className, maxInstances, startIndex)

    numInstances = len(inst_names)
    DEBUG("numInstances=%d startIndex=%d", numInstances, startIndex)

    # This displays one link on the same page, with specific values of these parameters.
    # The other parameters are not changed.
    # TODO, BEWARE: What is the total number of elements ?
    if startIndex + maxInstances < numInstances:
        cgiEnv.add_parameterized_links(
            "Next", {paramkeyStartIndex: startIndex + maxInstances})
    if startIndex > 0:
        cgiEnv.add_parameterized_links(
            "Previous",
            {paramkeyStartIndex: max(startIndex - maxInstances, 0)})

    # TODO: On pourrait rassembler par classes,
    # et aussi afficher les liens d'heritages des classes.

    # cgiEnv.OutCgiRdf()
    cgiEnv.OutCgiRdf("LAYOUT_RECT", [pc.property_class_instance])
Exemple #13
0
def Main():

	cgiEnv = lib_common.CgiEnv(can_process_remote = True)

	entity_id = cgiEnv.GetId()
	DEBUG("entity_id=%s", entity_id)
	if entity_id == "":
		lib_common.ErrorMessageHtml("No entity_id")


	# Just the path, shorter than cgiEnv.get_parameters("xid")
	cimomUrl = cgiEnv.GetHost()

	nameSpace, className = cgiEnv.get_namespace_type()
	DEBUG("entity_wbem.py cimomUrl=%s nameSpace=%s className=%s", cimomUrl,nameSpace,className)

	if nameSpace == "":
		nameSpace = "root/cimv2"
		INFO("Setting namespace to default value\n")


	if className == "":
		lib_common.ErrorMessageHtml("No class name. entity_id=%s" % entity_id)

	grph = cgiEnv.GetGraph()

	conn = lib_wbem.WbemConnection(cimomUrl)

	rootNode = lib_util.EntityClassNode( className, nameSpace, cimomUrl, "WBEM" )
	klaDescrip = lib_wbem.WbemClassDescription(conn,className,nameSpace)
	if not klaDescrip:
		klaDescrip = "Undefined class %s %s" % ( nameSpace, className )
	grph.add( ( rootNode, pc.property_information, lib_common.NodeLiteral(klaDescrip ) ) )

	splitMonik = lib_util.SplitMoniker( cgiEnv.m_entity_id )

	DEBUG("entity_wbem.py nameSpace=%s className=%s cimomUrl=%s",nameSpace,className,cimomUrl)

	# This works:
	# conn = pywbem.WBEMConnection("http://192.168.0.17:5988",("pegasus","toto"))
	# conn.ExecQuery("WQL","select * from CIM_System","root/cimv2")
	# conn.ExecQuery("WQL",'select * from CIM_Process  where Handle="4125"',"root/cimv2")
	#
	# select * from CIM_Directory or CIM_DataFile does not return anything.


	instLists = WbemPlainExecQuery( conn, className, splitMonik, nameSpace )
	DEBUG("entity_wbem.py instLists=%s",str(instLists))
	if instLists is None:
		instLists = WbemNoQueryOneInst( conn, className, splitMonik, nameSpace )
		if instLists is None:
			instLists = WbemNoQueryFilterInstances( conn, className, splitMonik, nameSpace )

	# TODO: Some objects are duplicated.
	# 'CSCreationClassName'   CIM_UnitaryComputerSystem Linux_ComputerSystem
	# 'CreationClassName'     PG_UnixProcess            TUT_UnixProcess
	numInsts = len(instLists)

	# If there are duplicates, adds a property which we hope is different.
	propDiscrim = "CreationClassName"

	# TODO!! WHAT OF THIS IS NOT THE RIGHT ORDER ???
	# Remove the double-quotes around the argument. WHAT IF THEY ARE NOT THERE ??
	# arrVals = [ ChopEnclosingParentheses( splitMonik[qryKey] ) for qryKey in splitMonik ]

	for anInst in instLists:

		# TODO: Use the right accessor for better performance.
		# On peut peut etre mettre tout ca dans une fonction sauf l execution de la query.
		dictInst = dict(anInst)

		# This differentiates several instance with the same properties.


		if numInsts > 1:
			# TODO: Should check if this property is different for all instances !!!
			withExtraArgs = { propDiscrim : dictInst[ propDiscrim ] }
			allArgs = splitMonik.copy()
			allArgs.update(withExtraArgs)
			dictProps = allArgs
		else:
			dictProps = splitMonik

		hostOnly = lib_util.EntHostToIp(cimomUrl)
		if lib_util.IsLocalAddress(hostOnly):
			uriInst = lib_common.gUriGen.UriMakeFromDict(className, dictProps)
		else:
			uriInst = lib_common.RemoteBox(hostOnly).UriMakeFromDict(className, dictProps)

		grph.add( ( rootNode, lib_common.MakeProp(className), uriInst ) )

		AddNamespaceLink(grph, rootNode, nameSpace, cimomUrl, className)

		# None properties are not printed.
		for inameKey in dictInst:
			# Do not print twice values which are in the name.
			if inameKey in splitMonik:
				continue
			inameVal = dictInst[inameKey]
			# TODO: If this is a reference, create a Node !!!!!!!
			if not inameVal is None:
				grph.add( ( uriInst, lib_common.MakeProp(inameKey), lib_common.NodeLiteral(inameVal) ) )

		# TODO: Should call Associators(). Same for References().

	cgiEnv.OutCgiRdf()
Exemple #14
0
def Main():
    paramkey_max_depth = "Maximum depth"
    paramkey_yawn_urls = "Yawn urls"

    # TODO: The type should really be an integer.
    cgiEnv = lib_common.ScriptEnvironment(can_process_remote=True,
                                          parameters={
                                              paramkey_max_depth: 2,
                                              paramkey_yawn_urls: False
                                          })

    wbem_namespace, entity_type = cgiEnv.get_namespace_type()

    max_depth = int(cgiEnv.get_parameters(paramkey_max_depth))
    with_yawn_urls = int(cgiEnv.get_parameters(paramkey_yawn_urls))

    logging.debug("wbem_namespace=%s entity_type=%s max_depth=%d",
                  wbem_namespace, entity_type, max_depth)

    cimom_url = cgiEnv.GetHost()

    if str(wbem_namespace) == "":
        lib_common.ErrorMessageHtml("namespace should not be empty.")

    grph = cgiEnv.GetGraph()

    try:
        conn_wbem = lib_wbem.WbemConnection(cimom_url)
    except Exception as exc:
        lib_common.ErrorMessageHtml("Connecting to :" + cimom_url +
                                    " Caught:" + str(exc))

    # entity_type might an empty string.
    root_node = _wbem_namespace_node(wbem_namespace, cimom_url, entity_type)

    logging.debug("cimom_url=%s entity_type=%s", cimom_url, entity_type)

    tree_classes_filtered = lib_wbem.GetClassesTreeInstrumented(
        conn_wbem, wbem_namespace)

    _print_class_recu(grph, root_node, tree_classes_filtered, entity_type, 0,
                      wbem_namespace, cimom_url, max_depth, with_yawn_urls)

    logging.debug("entity_type=%s", entity_type)

    # If we are not at the top of the tree:
    if entity_type != "":
        # Now, adds the base classes of this one, at least one one level.
        wbem_klass = lib_wbem.WbemGetClassObj(conn_wbem, entity_type,
                                              wbem_namespace)
        if wbem_klass:
            super_klass_name = wbem_klass.superclass

            logging.debug("super_klass_name=%s", super_klass_name)
            # An empty string or None.
            if super_klass_name:
                wbem_super_node = _wbem_namespace_node(wbem_namespace,
                                                       cimom_url,
                                                       super_klass_name)
                grph.add(
                    (wbem_super_node, pc.property_cim_subclass, root_node))
                kla_descrip = lib_wbem.WbemClassDescription(
                    conn_wbem, super_klass_name, wbem_namespace)
                if not kla_descrip:
                    kla_descrip = "Undefined class %s %s" % (wbem_namespace,
                                                             super_klass_name)
                grph.add((wbem_super_node, pc.property_information,
                          lib_util.NodeLiteral(kla_descrip)))

    cgiEnv.OutCgiRdf("LAYOUT_RECT_TB", [pc.property_cim_subclass])