Esempio n. 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()
Esempio n. 2
0
def CalcLabel(entity_host, entity_type, entity_id, force_entity_ip_addr,
              filScript):
    namSpac, entity_type_NoNS = lib_util.parse_namespace_type(entity_type)

    if not force_entity_ip_addr and not lib_util.IsLocalAddress(entity_host):
        entity_label = None
        if filScript == "entity_wbem.py":
            import lib_wbem
            # Because of WBEM, entity_host is a CIMOM url, like "http://vps516494.ovh.net:5988"
            entity_label = lib_wbem.EntityToLabelWbem(namSpac,
                                                      entity_type_NoNS,
                                                      entity_id, entity_host)
            if not entity_label:
                # Fallback to Survol label.
                actual_host = lib_util.EntHostToIp(entity_host)

                entity_label = EntityToLabel(entity_type_NoNS, entity_id,
                                             actual_host)
        elif filScript == "entity_wmi.py":
            import lib_wmi
            # For WMI, the hostname is a NETBIOS machine name.
            entity_label = lib_wmi.EntityToLabelWmi(namSpac, entity_type_NoNS,
                                                    entity_id, entity_host)
            if not entity_label:
                # Fallback to Survol label.
                actual_host = lib_util.EntHostToIp(entity_host)
                entity_label = EntityToLabel(entity_type_NoNS, entity_id,
                                             actual_host)
        else:
            # filScript in [ "class_type_all.py", "entity.py" ], or if no result from WMI or WBEM.
            entity_label = EntityToLabel(entity_type_NoNS, entity_id,
                                         entity_host)

    elif entity_type_NoNS or entity_id:
        entity_label = EntityToLabel(entity_type_NoNS, entity_id,
                                     force_entity_ip_addr)
    else:
        # Only possibility to print something meaningful.
        entity_label = namSpac

    # Some corner cases: "http://127.0.0.1/Survol/survol/entity.py?xid=CIM_ComputerSystem.Name="
    if not entity_label:
        entity_label = entity_type

    return entity_label
Esempio n. 3
0
def _calc_label(entity_host, entity_type, entity_id, force_entity_ip_addr, fil_script):
    """
    This calculates the label of an instance, also taking into account the script.
    """
    nam_spac, entity_type_no_ns = lib_util.parse_namespace_type(entity_type)

    if not force_entity_ip_addr and not lib_util.is_local_address(entity_host):
        entity_label = "Unset entity_label"
        if fil_script == "entity_wbem.py":
            import lib_wbem
            # Because of WBEM, entity_host is a CIMOM url, like "http://vps516494.ovh.net:5988"
            entity_label = lib_wbem.EntityToLabelWbem(nam_spac, entity_type_no_ns, entity_id, entity_host)
            if not entity_label:
                # Fallback to Survol label.
                actual_host = lib_util.EntHostToIp(entity_host)

                entity_label = entity_to_label(entity_type_no_ns, entity_id, actual_host)
        elif fil_script == "entity_wmi.py":
            import lib_wmi
            # For WMI, the hostname is a NETBIOS machine name.
            entity_label = lib_wmi.EntityToLabelWmi(nam_spac, entity_type_no_ns, entity_id, entity_host)
            if not entity_label:
                # Fallback to Survol label.
                actual_host = lib_util.EntHostToIp(entity_host)
                entity_label = entity_to_label(entity_type_no_ns, entity_id, actual_host)
        else:
            # filScript in [ "class_type_all.py", "entity.py" ], or if no result from WMI or WBEM.
            entity_label = entity_to_label(entity_type_no_ns, entity_id, entity_host)

    elif entity_type_no_ns or entity_id:
        entity_label = entity_to_label(entity_type_no_ns, entity_id, force_entity_ip_addr)
    else:
        # Only possibility to print something meaningful.
        entity_label = nam_spac

    # Some corner cases: "http://127.0.0.1/Survol/survol/entity.py?xid=CIM_ComputerSystem.Name="
    if not entity_label:
        entity_label = entity_type

    return entity_label
Esempio n. 4
0
def KnownScriptToTitle(filScript,
                       uriMode,
                       entity_host=None,
                       entity_suffix=None):
    # Extra information depending on the script.

    # Special display if MIME URL
    if filScript == "entity_mime.py":
        if not entity_suffix:
            entity_suffix = "None"
        # The Mime type is embedded into the mode, after a "mime:" prefix.
        entity_label = entity_suffix + " (" + lib_mime.ModeToMimeType(
            uriMode) + ")"
        return entity_label

    # The label is a Survol module name which is a class (With an EntityOntology() function),
    #  or a namespace. So we give the right title.
    if filScript == "class_type_all.py":
        moduOntology = lib_util.OntologyClassKeys(entity_suffix)
        if moduOntology:
            entity_label = entity_suffix + " (Class)"
        else:
            entity_label = entity_suffix + " (Domain)"
        return entity_label

    try:
        entity_label = scripts_to_titles[filScript]
    except KeyError:
        entity_label = filScript + "..."

    if entity_suffix:
        if entity_label:
            entity_label = entity_suffix + " (" + entity_label + ")"
        else:
            entity_label = entity_suffix

    # Maybe hostname is a CIMOM address (For WBEM) or a machine name.
    if entity_host:
        if not lib_util.IsLocalAddress(entity_host):
            # If this is a CIMOM, make it shorter: "http://vps516494.ovh.net:5988" or ""https://vps516494.ovh.net:5989"
            host_only = lib_util.EntHostToIp(entity_host)
            entity_label += " at " + host_only

    # TODO: Add the host name in the title.

    return entity_label
Esempio n. 5
0
def _create_wmi_node(grph, root_node, entity_host, name_space, class_name,
                     entity_id):
    """Adds a WMI node and other stuff, for the class name."""
    wmiurl = lib_wmi.GetWmiUrl(entity_host, name_space, class_name, entity_id)
    if wmiurl is None:
        return

    # There might be "http:" or the port number around the host.
    wmi_node = lib_common.NodeUrl(wmiurl)
    grph.add((root_node, pc.property_wmi_data, wmi_node))

    # TODO: Shame, we just did it in GetWmiUrl.
    ip_only = lib_util.EntHostToIp(entity_host)
    try:
        # It simply returns if it cannot connect.
        conn_wmi = lib_wmi.WmiConnect(ip_only, name_space, False)
        if not conn_wmi:
            raise Exception("Cannot connect")
        lib_wmi.WmiAddClassQualifiers(grph, conn_wmi, wmi_node, class_name,
                                      False)

        # Now displays the base classes, to the top of the inheritance tree.
        pair_name_node = lib_wmi.WmiAddBaseClasses(grph, conn_wmi, wmi_node,
                                                   ip_only, name_space,
                                                   class_name)

    except Exception as exc:
        pair_name_node = None
        # TODO: If the class is not defined, maybe do not display it.
        err_msg = "WMI connection %s: %s" % (ip_only, str(exc))
        grph.add((wmi_node, lib_common.MakeProp("WMI Error"),
                  lib_util.NodeLiteral(err_msg)))

    url_name_space = lib_wmi.NamespaceUrl(name_space, ip_only, class_name)
    grph.add((wmi_node, pc.property_information,
              lib_common.NodeUrl(url_name_space)))

    return pair_name_node
Esempio n. 6
0
def CreateWmiNode(grph, rootNode, entity_host, nameSpace, className,
                  entity_id):
    wmiurl = lib_wmi.GetWmiUrl(entity_host, nameSpace, className, entity_id)
    if wmiurl is None:
        return

    # There might be "http:" or the port number around the host.
    # hostOnly = lib_util.EntHostToIp(entity_host)
    # sys.stderr.write("entity_host=%s nameSpace=%s entity_type=%s className=%s wmiurl=%s\n" % ( entity_host, nameSpace, entity_type, className, str(wmiurl) ) )
    wmiNode = lib_common.NodeUrl(wmiurl)
    grph.add((rootNode, pc.property_wmi_data, wmiNode))

    # TODO: Shame, we just did it in GetWmiUrl.
    ipOnly = lib_util.EntHostToIp(entity_host)
    try:
        # It simply returns if it cannot connect.
        connWmi = lib_wmi.WmiConnect(ipOnly, nameSpace, False)
        lib_wmi.WmiAddClassQualifiers(grph, connWmi, wmiNode, className, False)

        # Now displays the base classes, to the top of the inheritance tree.
        pairNameNode = lib_wmi.WmiAddBaseClasses(grph, connWmi, wmiNode,
                                                 ipOnly, nameSpace, className)

    except Exception:
        pairNameNode = None
        # TODO: If the class is not defined, maybe do not display it.
        exc = sys.exc_info()[1]
        grph.add((wmiNode, lib_common.MakeProp("WMI Error"),
                  lib_common.NodeLiteral(str(exc))))

    urlNameSpace = lib_wmi.NamespaceUrl(nameSpace, ipOnly, className)
    # sys.stderr.write("entity_host=%s urlNameSpace=%s\n"%(entity_host,urlNameSpace))
    grph.add(
        (wmiNode, pc.property_information, lib_common.NodeUrl(urlNameSpace)))

    return pairNameNode
Esempio n. 7
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()
Esempio n. 8
0
    # 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

    # uriInst = lib_util.EntityUriFromDict( className, dictProps  )
    # uriInst = lib_common.RemoteBox(cimomUrl).UriMakeFromDict(className, dictProps)

    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)

    # PEUT-ETRE UTILISER LA VERITABLE CLASSE, MAIS IL FAUT PART LA SUITE ATTEINDRE LA CLASSE DE BASE.
    grph.add((rootNode, lib_common.MakeProp(className), uriInst))

    # 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]
Esempio n. 9
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()
Esempio n. 10
0
def NormalHostName(entity_host):
    if entity_host == "":
        # Typically returns "RCHATEAU-HP".
        # Could also use platform.node() or socket.gethostname() or os.environ["COMPUTERNAME"]
        entity_host = socket.gethostname()
    return lib_util.EntHostToIp(entity_host)