示例#1
0
def _build_fc_switch_osh(switch):
    '@types: Switch -> osh'
    ipAddress = switch.address
    if ipAddress and ip_addr.isValidIpAddress(ipAddress):
        fcSwitchOSH = modeling.createHostOSH(str(ipAddress), 'fcswitch')
    else:
        logger.debug('IP address not available for Switch <%s> with ID <%s>!! Creating Switch with ID as primary key...' % (switch.name, switch.id))
        hostKey = switch.id + ' (ECC ID)'
        fcSwitchOSH = modeling.createCompleteHostOSH('fcswitch', hostKey)
        fcSwitchOSH.setAttribute('data_note', 'IP address unavailable in ECC - Duplication of this CI is possible')

    used_ports = None
    if switch.portcount != None and switch.portcount_free != None:
        used_ports = switch.portcount - switch.portcount_free

    populateOSH(fcSwitchOSH, {
        'data_description': switch.sn,
        'fcswitch_wwn': switch.sn,
        'data_name': switch.name,
        'host_model': switch.host_model,
        'fcswitch_version': switch.version,
        'host_vendor': switch.host_vendor,
        'fcswitch_domainid': switch.domain_id,
        'fcswitch_availableports': switch.portcount,
        'fcswitch_freeports': switch.portcount_free,
        'fcswitch_connectedports': used_ports
    })
    fcSwitchOSH.setListAttribute('node_role', ['switch'])
    return fcSwitchOSH
示例#2
0
 def build(self):
     if self.ipAddress and self.queueName:
         self.hostOsh = modeling.createHostOSH(self.ipAddress)
         self.msMqManagerOsh = modeling.createApplicationOSH('msmqmanager', 'Microsoft MQ Manager', self.hostOsh)
         self.queueOsh = ObjectStateHolder('msmqqueue')
         self.queueOsh.setAttribute('data_name', self.queueName.lower())
         self.queueOsh.setContainer(self.msMqManagerOsh)
示例#3
0
def doReadFile(shellUtils, fileName, OSHVResult, tnsFile):

	tns_entries = dbutils.parseTNSNames(tnsFile, '', shellUtils)
#	parseTnsEntries(fileName, shellUtils, tns_entries, OSHVResult)
	if (len(tns_entries)==0):
		logger.info('no entries returns from ',  fileName, '. Please verify if the file exists and it is valid TNS file.')
		return

	logger.debug('Found ', len(tns_entries), ' entries in tnsnames.ora file.')
	oracleList = []
	for tns_entry in tns_entries:
		try:
			db_type	= 'oracle'
			connectString = tns_entry[0]
			host_dns= tns_entry[1]
			db_port	= tns_entry[2]
			db_sid	= tns_entry[3].upper()
			host_ip	= tns_entry[5]
			if (netutils.isValidIp(host_ip)):
				hashName = host_ip + db_sid
				if ((hashName in oracleList) == 0) :
					oracleList.append(hashName)
					hostOSH = modeling.createHostOSH(host_ip)
					oracleOSH = modeling.createDatabaseOSH(db_type, db_sid, db_port, host_ip, hostOSH)
					oracleOSH.setAttribute('database_dbconnectstring', connectString)
					oracleOSH.setContainer(hostOSH)
					OSHVResult.add(hostOSH)
					OSHVResult.add(oracleOSH)
			else:
				logger.warn("Can not resolve the IP from the TNS entry's host name (", host_dns, ") - TNS entry skipped.")

		except:
			logger.debugException('Unexpected TNS Parsing Exception:')
示例#4
0
    def discoverReplication(self, mysqlOsh):
        """
        Tries to find config variables related to mysql replication 
        @param ObjectStateHolder mysqlOsh mysql osh
        @return list list of OSHs
        """
        masterHostIp = self.getProperty('master-host')
        if not masterHostIp:
            return 
        if not netutils.isValidIp(masterHostIp):
            try:
                resolver = netutils.DnsResolverByShell(self.shell)
                masterHostIp = resolver.resolveIpsByHostname(masterHostIp)[0]
            except netutils.ResolveException:
                logger.warn('Failed to resolve Master Host into IP')
                return
        masterPort = self.getProperty('master-port')
        mysqlReplicationOsh = ObjectStateHolder('mysql_replication')
        mysqlReplicationOsh.setAttribute('data_name', 'MySQL Replication')
        mysqlReplicationOsh.setContainer(mysqlOsh)
        self.setAttribute(mysqlReplicationOsh, 'master_user', self.REPL_ARGS_MAPPING)
        self.setAttribute(mysqlReplicationOsh, 'master_connect_retry', self.REPL_ARGS_MAPPING)
        masterHostOsh = modeling.createHostOSH(masterHostIp)
        serviceAddressOsh = modeling.createServiceAddressOsh(masterHostOsh, masterHostIp, masterPort, modeling.SERVICEADDRESS_TYPE_TCP)
        clientServerLink = modeling.createLinkOSH('client_server', mysqlReplicationOsh, serviceAddressOsh)
        clientServerLink.setStringAttribute('clientserver_protocol', 'TCP')
        clientServerLink.setLongAttribute('clientserver_destport', int(masterPort))
#        masterMysqlOsh = modeling.createDatabaseOSH('mysql', 'MySQL. Port ' + masterPort, masterPort, masterHostIp, masterHostOsh)
#        useLink = modeling.createLinkOSH('use', masterHostOsh, serviceAddressOsh)
        return [masterHostOsh, serviceAddressOsh, clientServerLink, mysqlReplicationOsh]
示例#5
0
def createIPEndpointOSHV(framework,
                         ipAddress,
                         portNum,
                         portName,
                         hostname=None,
                         protocol=modeling.SERVICEADDRESS_TYPE_TCP):
    OSHVResult = ObjectStateHolderVector()
    if ip_addr.isValidIpAddress(hostname):
        hostname = None

    fqdn, aliasList = getHostNames(ipAddress, framework)

    hostOSH = modeling.createHostOSH(ipAddress, 'node', None, fqdn)
    ipOSH = modeling.createIpOSH(ipAddress, None, fqdn)
    link = modeling.createLinkOSH('containment', hostOSH, ipOSH)

    OSHVResult.add(hostOSH)
    OSHVResult.add(ipOSH)
    OSHVResult.add(link)

    ipPort = modeling.createServiceAddressOsh(hostOSH, ipAddress, portNum,
                                              protocol, portName)
    if fqdn:
        ipPort.setStringAttribute('ipserver_address', fqdn)

    if isValidFQDN(hostname):
        ipPort.setStringAttribute('ipserver_address', hostname)

    #ipPort.addAttributeToList('itrc_alias', sv)
    #ipOSH.addAttributeToList('itrc_alias', sv)

    #OSHVResult.add(modeling.createLinkOSH('usage', ipPort, ipOSH))
    OSHVResult.add(ipPort)

    return hostOSH, ipOSH, OSHVResult
示例#6
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()

    ip_address = Framework.getDestinationAttribute('ip_address')
    
    hostOSH = modeling.createHostOSH(ip_address)
    
    protocols = Framework.getAvailableProtocols(ip_address, ClientsConsts.SQL_PROTOCOL_NAME)
    
    for sqlProtocol in protocols:
        dbClient = None
        try:
            try:
                if dbutils.protocolMatch(Framework, sqlProtocol, 'sybase', None, None) == 0:
                    continue

                dbClient = Framework.createClient(sqlProtocol)
                logger.debug('Connnected to sybase on ip ', dbClient.getIpAddress(), ', port ', str(dbClient.getPort()), ' to database ',dbClient.getDatabaseName(),'with user ', dbClient.getUserName())
                dbversion = dbClient.getDbVersion()
                
                logger.debug('Found sybase server of version:', dbversion)
                res = dbClient.executeQuery("select srvnetname from master..sysservers where srvid = 0")#@@CMD_PERMISION sql protocol execution
                if res.next():
                    dbname=string.strip(res.getString(1))
                    sybasedOSH = modeling.createDatabaseOSH('sybase', dbname, str(dbClient.getPort()),dbClient.getIpAddress(),hostOSH,sqlProtocol,dbClient.getUserName(),None,dbversion)
                    OSHVResult.add(sybasedOSH)
                else:
                    Framework.reportWarning('Sybase server was not found')
            except MissingJarsException, e:
                logger.debugException(e.getMessage())
                Framework.reportError(e.getMessage())
                return
            except:
                logger.debugException('Failed to discover sybase with credentials ', sqlProtocol)
        finally:
示例#7
0
def createIPEndpointOSHV(framework, ipAddress, portNum, portName, hostname = None, protocol = modeling.SERVICEADDRESS_TYPE_TCP):
    OSHVResult = ObjectStateHolderVector()
    if ip_addr.isValidIpAddress(hostname):
        hostname = None
    
    fqdn, aliasList = getHostNames(ipAddress, framework)
    
    hostOSH = modeling.createHostOSH(ipAddress, 'node', None, fqdn)
    ipOSH = modeling.createIpOSH(ipAddress, None, fqdn)
    link = modeling.createLinkOSH('containment', hostOSH, ipOSH)
    
    OSHVResult.add(hostOSH)
    OSHVResult.add(ipOSH)
    OSHVResult.add(link)
    
    ipPort = modeling.createServiceAddressOsh(hostOSH, ipAddress, portNum, protocol, portName)
    if fqdn:
        ipPort.setStringAttribute('ipserver_address', fqdn)
    
    if isValidFQDN(hostname):         
        ipPort.setStringAttribute('ipserver_address', hostname)
    
    #ipPort.addAttributeToList('itrc_alias', sv)
    #ipOSH.addAttributeToList('itrc_alias', sv)        
         
    #OSHVResult.add(modeling.createLinkOSH('usage', ipPort, ipOSH)) 
    OSHVResult.add(ipPort)
   
    return hostOSH, ipOSH, OSHVResult
示例#8
0
def executeWmiQuery(client, OSHVResult, nodeOsh=None):
    '''
    @deprecated: Use NTCMD_HR_Dis_Disk_Lib.discoverDiskByWmic instead
    '''
    containerOsh = nodeOsh or modeling.createHostOSH(client.getIpAddress())
    NTCMD_HR_Dis_Disk_Lib.discoverDiskByWmic(client, OSHVResult, containerOsh)
    NTCMD_HR_Dis_Disk_Lib.discoverPhysicalDiskByWmi(client, OSHVResult, containerOsh)
示例#9
0
def executeWmiQuery(client, OSHVResult, nodeOsh=None):
    '''Client, ObjectStateHolderVector
    @command: select Capacity from Win32_PhysicalMemory
    '''
    containerOsh = nodeOsh or modeling.createHostOSH(client.getIpAddress())
    resultSet = client.executeQuery("select Capacity from Win32_PhysicalMemory"
                                    )  #@@CMD_PERMISION wmi protocol execution
    memoryCounter = 0
    sizeInKb = 0
    while resultSet.next():
        memoryCounter = memoryCounter + 1
        # physical memory in bytes
        if resultSet.getString(1):
            sizeInKb += int(resultSet.getLong(1) / 1024)
    if sizeInKb:
        memory.report(OSHVResult, containerOsh, sizeInKb)
    logger.debug("Discovered ", memoryCounter, " memory slots")

    swapMemorySize = 0
    resultSet = client.executeQuery(
        "select MaximumSize from Win32_PageFileSetting"
    )  #@@CMD_PERMISION wmi protocol execution
    while resultSet.next():
        swapMemorySize += int(resultSet.getLong(1))
    modeling.setHostSwapMemorySizeAttribute(containerOsh, swapMemorySize)

    OSHVResult.add(containerOsh)
示例#10
0
def createFsmHostOsh(fsmHost, ipAddress):
    """
    Creates the Object State Holder of the host where IBM HMC Management Sortware runs
    @param fsmHost: discovered host where IBM HMC runs
    @type fsmHost: instance of Host Data Object
    @param ipAddres: the IP Address of the Host
    @type ipAddress: String
    @return: Object State Holde of the UNIX CI instance
    """
    if fsmHost and ipAddress:
        hostOsh = modeling.createHostOSH(ipAddress, 'unix', None, fsmHost.hostname)
        hostOsh.setStringAttribute('vendor', 'ibm_corp')
        hostOsh.setStringAttribute("os_family", 'unix')
        if fsmHost.domainName:
            hostOsh.setStringAttribute('host_osdomain', fsmHost.domainName)
        if fsmHost.fsmSoftware:
            
#            if fsmHost.fsmSoftware.bios:
#                hostOsh.setStringAttribute('bios_serial_number', fsmHost.fsmSoftware.bios)
                
            if fsmHost.fsmSoftware.versionInformation:
                if fsmHost.fsmSoftware.versionInformation.fullVersion:
                    hostOsh.setStringAttribute('host_osrelease', fsmHost.fsmSoftware.versionInformation.fullVersion)
                if fsmHost.fsmSoftware.versionInformation.baseOSVersion:
                    hostOsh.setStringAttribute('discovered_os_version', fsmHost.fsmSoftware.versionInformation.baseOSVersion)
                    
            if fsmHost.fsmSoftware.typeInformation and fsmHost.fsmSoftware.typeInformation.serialNum:
                hostOsh.setStringAttribute('serial_number', fsmHost.fsmSoftware.typeInformation.serialNum)
                
        return hostOsh
    else:
        logger.reportError('Failed to discover FSM Host')
        raise ValueError("Failed to discover FSM Host")
示例#11
0
def buildDBObjects(db_type, host_ip, db_port, db_name, db_sid, appServerOSH,
                   OSHVResult):
    logger.debug('building TNS Entry ', db_type, host_ip, db_name, db_port,
                 db_sid)

    oshs = []
    hostOSH = modeling.createHostOSH(host_ip)
    oshs.append(hostOSH)
    dbOSH, ipseOsh, databaseOshs = None, None, None

    platform = db_platform.findPlatformBySignature(db_type)
    if not platform:
        logger.warn("Failed to determine platform for %s" % db_type)
    else:
        dbserver = db_builder.buildDatabaseServerPdo(db_type, db_name, host_ip,
                                                     db_port)
        if not db_name and not db_port:
            builder = db_builder.Generic()
        else:
            builder = db_builder.getBuilderByPlatform(platform)

        dbTopologyReporter = db.TopologyReporter(builder)
        result = dbTopologyReporter.reportServerWithDatabases(
            dbserver, hostOSH, (appServerOSH, ))
        dbOSH, ipseOsh, databaseOshs, vector_ = result
        oshs.extend(vector_)

    OSHVResult.addAll(oshs)
示例#12
0
def build_network_device(device):
    '''
    Build Layer 2 connection end.
    @type param: NetworkDevice -> OSH
    '''
    device_osh = None
    device_ip_address_osh = None
    device_interface_osh = None
    device_member_ip = None
    if device.ucmdb_id:
        device_osh = modeling.createOshByCmdbIdString('node', device.ucmdb_id)
    if device.mac_address:
        if not device_osh:
            device_osh = modeling.createCompleteHostOSH(
                'node', device.mac_address)
        device_interface_osh = modeling.createInterfaceOSH(
            device.mac_address, device_osh)
    if device.ip_address:
        if not device_osh:
            device_osh = modeling.createHostOSH(device.ip_address)
        device_ip_address_osh = modeling.createIpOSH(device.ip_address)
        device_member_ip = modeling.createLinkOSH('contained', device_osh,
                                                  device_ip_address_osh)
    if device.port:
        if device_interface_osh:
            device_interface_osh.setAttribute('interface_name', device.port)
        elif device_osh:
            device_interface_osh = ObjectStateHolder('interface')
            device_interface_osh.setContainer(device_osh)
            device_interface_osh.setAttribute('interface_name', device.port)
    return device_osh, device_ip_address_osh, device_interface_osh, device_member_ip
    def process(self, context):
        poolOSHV = modelApplicationPool(context)
        if poolOSHV:
            context.resultsVector.addAll(poolOSHV)
        endpointOSHV = modelConnectedPortByPowerShell(
            context) or modelConnectedPortByAppcmd(context)
        if endpointOSHV:
            context.resultsVector.addAll(endpointOSHV)
        client = context.client
        iisVersion = get_iis_version_by_reg(client)
        if iisVersion:
            self.applicationOsh.setAttribute("application_version_number",
                                             iisVersion)
        else:
            processes = context.application.getProcesses()
            for process in processes:
                fullFileName = process.executablePath
                iisVersion = self.getVersion(client, fullFileName)
                if iisVersion:
                    self.applicationOsh.setAttribute(
                        "application_version_number", iisVersion)
                    break

        logger.debug("application ip:", context.application.getApplicationIp())
        hostOsh = modeling.createHostOSH(
            context.application.getApplicationIp())
        self.applicationOsh.setContainer(hostOsh)
    def process(self, context):
        poolOSHV = modelApplicationPool(context)
        if poolOSHV:
            context.resultsVector.addAll(poolOSHV)
        client = context.client
        iisVersion = get_iis_version_by_reg(client)
        if iisVersion:
            self.applicationOsh.setAttribute("application_version_number",
                                             iisVersion)
        else:
            processes = context.application.getProcesses()
            for process in processes:
                fullFileName = process.executablePath
                if fullFileName:
                    fileVer = file_ver_lib.getWindowsWMIFileVer(
                        client, fullFileName)
                    if fileVer:
                        validVer = re.match('\s*(\d+\.\d+)', fileVer)
                        if validVer and validVer.group(1):
                            self.applicationOsh.setAttribute(
                                "application_version_number",
                                validVer.group(1))
                            break

        logger.debug("application ip:", context.application.getApplicationIp())
        hostOsh = modeling.createHostOSH(
            context.application.getApplicationIp())
        self.applicationOsh.setContainer(hostOsh)
def doDiscovery(Framework, shell, ip, credentialId, codepage, shellName, warningsList, errorsList, uduid = None):
    vector = ObjectStateHolderVector()
    try:
        try:
            languageName = shell.osLanguage.bundlePostfix

            langBund = Framework.getEnvironmentInformation().getBundle('langNetwork', languageName)
                             
            remoteHostnames = dns_resolver.NsLookupDnsResolver(shell).resolve_hostnames(ip)
            remoteHostFqdn = None 
            if remoteHostnames:
                remoteHostFqdn = remoteHostnames[0]
            shellObj = createShellObj(shell, ip, langBund, languageName, codepage, remoteHostFqdn)
            try:
                vector.addAll(discover(shell, shellObj, ip, langBund, Framework, uduid))
            finally:
                # create shell OSH if connection established
                if shellObj and not vector.size():
                    hostOsh = modeling.createHostOSH(ip)
                    shellObj.setContainer(hostOsh)
                    vector.add(shellObj)
        except Exception, ex:
            strException = ex.getMessage()
            errormessages.resolveAndAddToObjectsCollections(strException, shellName, warningsList, errorsList)
        except:
            msg = str(sys.exc_info()[1])
            logger.debugException('')
            errormessages.resolveAndAddToObjectsCollections(msg, shellName, warningsList, errorsList)
def modelConnectedPortByPowerShell(context):
    endpointOSHV = ObjectStateHolderVector()
    try:
        logger.debug("reporting endpoints for iis using powershell")
        shell = NTCMD_IIS.CscriptShell(context.client)
        system32Location = shell.createSystem32Link() or '%SystemRoot%\\system32'
        discoverer = iis_powershell_discoverer.get_discoverer(shell)
        if isinstance(discoverer, iis_powershell_discoverer.PowerShellOverNTCMDDiscoverer):
            discoverer.system32_location = system32Location
        executor = discoverer.get_executor(shell)
        sites_info = iis_powershell_discoverer.WebSitesCmd() | executor
        for site_info in sites_info:
            site_name = site_info.get("name")
            if site_name:
                bindings = iis_powershell_discoverer.WebSiteBindingCmd(site_name) | executor
                host_ips = []
                host_ips.append(context.application.getApplicationIp())
                logger.debug("application ip", context.application.getApplicationIp())
                parse_func = partial(iis_powershell_discoverer.parse_bindings, host_ips=host_ips)
                bindings = map(parse_func, bindings)
                for binding in bindings:
                    logger.debug("reporting binding:", binding[2])
                    for bind in binding[2]:
                        endpointOSH = visitEndpoint(bind)
                        hostosh = context.application.getHostOsh()
                        ip = bind.getAddress()
                        hostosh = modeling.createHostOSH(ip)
                        endpointOSH.setContainer(hostosh)
                        linkOsh = modeling.createLinkOSH("usage", context.application.getOsh(), endpointOSH)
                        endpointOSHV.add(endpointOSH)
                        endpointOSHV.add(linkOsh)

    except Exception, ex:
        logger.debug("Cannot get port from powershell:", ex)
        return None
示例#17
0
def buildDBObjects(db_type, host_ip, db_port, db_name, db_sid, appServerOSH, OSHVResult):
	logger.debug('building TNS Entry ', db_type, host_ip, db_name, db_port, db_sid)

	oshs = []
	hostOSH = modeling.createHostOSH(host_ip)
	oshs.append(hostOSH)
	dbOSH, ipseOsh, databaseOshs = None, None, None

	platform = db_platform.findPlatformBySignature(db_type)
	if not platform:
		logger.warn("Failed to determine platform for %s" % db_type)
	else:
		dbserver = db_builder.buildDatabaseServerPdo(db_type, db_name, host_ip, db_port)
		if not db_name and not db_port:
			builder = db_builder.Generic()
		else:
			builder = db_builder.getBuilderByPlatform(platform)

		dbTopologyReporter = db.TopologyReporter(builder)
		result = dbTopologyReporter.reportServerWithDatabases(dbserver,
															  hostOSH,
															  (appServerOSH,))
		dbOSH, ipseOsh, databaseOshs, vector_ = result
		oshs.extend(vector_)

	OSHVResult.addAll(oshs)
示例#18
0
    def getTopology(self, ipAddress):
        lb = modeling.createHostOSH(ipAddress, 'host')
        cisco_ace = modeling.createApplicationOSH('cisco_ace', 'Cisco_ACE', lb, 'Load Balance', 'Cisco')
        self.OSHVResult.add(lb)
        self.OSHVResult.add(cisco_ace)

        self.discoverVirtualServers(cisco_ace)
示例#19
0
    def _createHostOsh(self):
        ''' method creates containing host OSH depending on settings in XML and discovered data '''

        appComponent = self.getApplicationComponent()

        if appComponent.isClustered():
            # clustered applications should use weak hosts by IP
            hostIp = self._applicationIp

            if hostIp and ip_addr.IPAddress(hostIp).get_is_private():
                hostIp = self.getConnectionIp()

            if not hostIp:
                raise applications.ApplicationSignatureException("Cannot report application since no valid host IP is found")

            logger.debug(" -- clustered application uses host by IP '%s'" % hostIp)

            self.hostOsh = modeling.createHostOSH(hostIp)
        else:
            # non-clustered applications use host by hostId

            self.hostOsh = self.getApplicationComponent().getHostOsh()
            logger.debug(self.hostOsh)

            if self.hostOsh:
                logger.debug(" -- application uses host by Host OSH")
            else:
                logger.debug(" -- application uses host by CMDB ID")
                hostId = self.getApplicationComponent().getHostId()
                if hostId:
                    self.hostOsh = modeling.createOshByCmdbIdString('host', hostId)
    def process(self, context):
        '''
        Plugin gets system information from DEFAULT profile. In case if profile
        cannot be processed - system information is parsed from instance
        profile path.

        Default profile read for system (identified by its path) is shared
        between application component instances
        '''
        shell = context.client
        osh = context.application.applicationOsh
        host_osh = context.hostOsh
        attrName = sap.InstanceBuilder.INSTANCE_PROFILE_PATH_ATTR
        pf_path = osh.getAttributeValue(attrName)
        logger.info("Instance pf path is: %s" % pf_path)
        system, pf_name = sap_discoverer.parsePfDetailsFromPath(pf_path)
        logger.info("Parsed details from pf name: %s" % str((system, pf_name)))
        topology = self._discover_topology(shell, system, pf_path)
        if topology:
            #resolver = dns_resolver.SocketDnsResolver()
            resolver = dns_resolver.create(shell, local_shell=None,
                                   dns_server=None,
                                   hosts_filename=None)

            db_host_osh, oshs = _report_db_host(topology, resolver)
            application_ip = _report_application_ip(shell, topology, resolver)
            if application_ip:
                logger.info("application ip is: %s" % application_ip)
                osh.setAttribute('application_ip', str(application_ip))
                host_app_osh = modeling.createHostOSH(str(application_ip))
                logger.info("set container: %s" % host_app_osh)
                osh.setContainer(host_app_osh)
            oshs.extend(self._report_topology(osh, host_osh, db_host_osh, topology))
            context.resultsVector.addAll(oshs)
示例#21
0
    def _createHostOsh(self):
        ''' method creates containing host OSH depending on settings in XML and discovered data '''

        appComponent = self.getApplicationComponent()

        if appComponent.isClustered():
            # clustered applications should use weak hosts by IP
            hostIp = self._applicationIp

            if hostIp and ip_addr.IPAddress(hostIp).get_is_private():
                hostIp = self.getConnectionIp()

            if not hostIp:
                raise applications.ApplicationSignatureException(
                    "Cannot report application since no valid host IP is found"
                )

            logger.debug(" -- clustered application uses host by IP '%s'" %
                         hostIp)

            self.hostOsh = modeling.createHostOSH(hostIp)
        else:
            # non-clustered applications use host by hostId

            self.hostOsh = self.getApplicationComponent().getHostOsh()
            logger.debug(self.hostOsh)

            if self.hostOsh:
                logger.debug(" -- application uses host by Host OSH")
            else:
                logger.debug(" -- application uses host by CMDB ID")
                hostId = self.getApplicationComponent().getHostId()
                if hostId:
                    self.hostOsh = modeling.createOshByCmdbIdString(
                        'host', hostId)
示例#22
0
def doQuerySoftware(client, OSHVResult):
    _hostObj = modeling.createHostOSH(client.getIpAddress())
    softwareList = []
    # going over: .iso.org.dod.internet.mgmt.mib-2.host.hrSWInstalled.hrSWInstalledTable.hrSWInstalledEntry
    # and getting the following:	 hrSWInstalledName                      hrSWInstalledID               hrSWInstalledType             hrSWInstalledDate
    data_name_mib = '1.3.6.1.2.1.25.6.3.1.2,1.3.6.1.2.1.25.6.3.1.3,string,1.3.6.1.2.1.25.6.3.1.3,string,1.3.6.1.2.1.25.6.3.1.4,string,1.3.6.1.2.1.25.6.3.1.5,hexa'
    resultSet = client.executeQuery(
        data_name_mib)  # @@CMD_PERMISION snmp protocol execution
    while resultSet.next():
        data_name = resultSet.getString(2)
        if isHexadecimalName(data_name):
            continue
        software_productid = None
        if resultSet.getString(3) != '0.0':
            software_productid = resultSet.getString(3)
        software_type = resultSet.getString(4)
        software_date = dateConvert(resultSet.getString(5))
        if data_name and ((data_name in softwareList) == 0):
            softwareList.append(data_name)
            swOSH = hostresource.doSoftware(_hostObj, data_name,
                                            software_productid, software_type,
                                            software_date)
            OSHVResult.add(swOSH)
        else:
            logger.debug('software: ', data_name, ' already reported..')
示例#23
0
 def buildDbClient(self, dbClient):
     if not dbClient:
         raise ValueError('DB Client is not specified')
     host = dbClient.getHost()
     hostOsh = modeling.createHostOSH(host)
     processOsh = modeling.createProcessOSH(dbClient.getName(), hostOsh)
     return processOsh
    def reporterMSCluster(self, vector, ms_cluster, groups, ipDictByGroupName, nodesWithIP):
        clusterOsh = ms_cluster.create_osh()
        vector.add(clusterOsh)
        vector.add(modeling.createLinkOSH('membership', clusterOsh, self.applicationOsh))

        for node in nodesWithIP:
            ips = nodesWithIP[node]
            hostOsh = (modeling.createHostOSH(str(ips[0]), 'nt')
                       or ObjectStateHolder('nt'))
            hostOsh.setStringAttribute('name', node)
            hostOsh.setStringAttribute('os_family', 'windows')
            for ip_obj in ips:
                ipOSH = modeling.createIpOSH(ip_obj)
                vector.add(ipOSH)
                vector.add(modeling.createLinkOSH('containment', hostOsh, ipOSH))
            softwareOsh = modeling.createClusterSoftwareOSH(hostOsh,
                                                            'Microsoft Cluster SW', ms_cluster.version)
            softwareOsh.setAttribute("application_version_number", ms_cluster.version)
            vector.add(softwareOsh)
            vector.add(modeling.createLinkOSH('membership', clusterOsh, softwareOsh))

        for group in groups:
            ips = ipDictByGroupName.get(group.name, None)
            if ips:
                for ip in ips:
                    groupOsh = group.create_osh()
                    vector.add(groupOsh)
                    vector.add(modeling.createLinkOSH('contained', clusterOsh, groupOsh))

                    ipOsh = modeling.createIpOSH(ip)
                    vector.add(modeling.createLinkOSH('contained', groupOsh, ipOsh))
                    vector.add(ipOsh)
                    self.__crgMap[str(ip)] = groupOsh
示例#25
0
def reportRemotePeer(remote_peer, localInterfaceOsh, local_mac):
    vector = ObjectStateHolderVector()
    if remote_peer.peer_ips:
        hostOsh = modeling.createHostOSH(str(remote_peer.peer_ips[0]))
    if remote_peer.platform in VIRTUAL_HOST_PLATFORMS:
        hostOsh.setBoolAttribute('host_isvirtual', 1)
        vector.add(hostOsh)
        for ip in remote_peer.peer_ips:
            ipOsh = modeling.createIpOSH(ip)
            linkOsh = modeling.createLinkOSH('containment', hostOsh, ipOsh)
            vector.add(ipOsh)
            vector.add(linkOsh)
    else:
        hostOsh = ObjectStateHolder('node')
        hostOsh.setBoolAttribute('host_iscomplete', 1)
        hostOsh.setStringAttribute('name', remote_peer.system_name)
        if remote_peer.platform in VIRTUAL_HOST_PLATFORMS:
            hostOsh.setBoolAttribute('host_isvirtual', 1)
        vector.add(hostOsh)
    
    if remote_peer.interface_name or remote_peer.interface_mac:
        remoteInterfaceOsh = modeling.createInterfaceOSH(mac = remote_peer.interface_mac, hostOSH = hostOsh, name = remote_peer.interface_name)
        if not remoteInterfaceOsh:
            return ObjectStateHolderVector()
        if remote_peer.interface_name:
            remoteInterfaceOsh.setStringAttribute('name', remote_peer.interface_name)
        vector.add(remoteInterfaceOsh)
        l2id = str(hash(':'.join([remote_peer.interface_mac or remote_peer.interface_name, local_mac])))
        vector.addAll(reportLayer2Connection(localInterfaceOsh, remoteInterfaceOsh, l2id))
    return vector
示例#26
0
def osh_createiSeriesOsh(defaultIp,  model, osversion, serialnbr,sysname, macAddress):

    # Create Iseries OSH ----------------------------------
    str_discovered_os_name = 'discovered_os_name'
    str_discovered_os_version = 'discovered_os_version'
    str_discovered_os_vendor = 'discovered_os_vendor'
    str_discovered_model = 'discovered_model'
    str_vendor = 'vendor'
    str_os_vendor = 'os_vendor'
    str_name = 'name'
    host_key = 'host_key'
    str_serialnbr = 'serial_number'
    
    isComplete = 1    
    os400Osh = modeling.createHostOSH(defaultIp, 'as400_node', _STR_EMPTY, _STR_EMPTY, _STR_EMPTY)
    os400Osh.setAttribute(str_discovered_os_name, 'os/400')
    os400Osh.setBoolAttribute('host_iscomplete', isComplete)
    os400Osh.setAttribute(str_discovered_os_version, osversion)
    os400Osh.setAttribute(str_discovered_model, model)
    os400Osh.setAttribute(str_os_vendor, 'IBM')
    os400Osh.setAttribute(str_discovered_os_vendor, 'IBM')
    os400Osh.setAttribute(str_vendor, 'IBM')
    os400Osh.setAttribute(str_name, sysname )
    os400Osh.setAttribute(str_serialnbr, serialnbr )     
    os400Osh.setAttribute(host_key, macAddress )   
    
    return os400Osh
示例#27
0
    def discoverServices(self):
        serviceQueryBuilder = SnmpQueryBuilder(SVC_OID_OFFSET)
        serviceQueryBuilder.addQueryElement(1, 'svc_name')
        serviceQueryBuilder.addQueryElement(3, 'ip')
        serviceQueryBuilder.addQueryElement(4, 'protocol')
        serviceQueryBuilder.addQueryElement(5, 'port')
        serviceQueryBuilder.addQueryElement(41, 'ip_range')
        serviceQueryBuilder.addQueryElement(42, 'port_range')

        snmpRowElements = self.snmpAgent.getSnmpData(serviceQueryBuilder)

        poolMemberToPoolQueryBuilder = SnmpQueryBuilder(CNTSVC_OID_OFFSET)
        poolMemberToPoolQueryBuilder.addQueryElement(2, 'cnt_name')
        poolMemberToPoolQueryBuilder.addQueryElement(3, 'svc_name')
        poolMemberToPoolElements = self.snmpAgent.getSnmpData(
            poolMemberToPoolQueryBuilder)

        svcToCntMap = {}
        for poolMemberToPoolElement in poolMemberToPoolElements:
            cnt = self.resourcePools[poolMemberToPoolElement.cnt_name]
            cntList = svcToCntMap.get(poolMemberToPoolElement.svc_name, [])
            cntList.append(cnt)
            svcToCntMap[poolMemberToPoolElement.svc_name] = cntList

        for snmpRowElement in snmpRowElements:
            poolMember = modeling.createHostOSH(snmpRowElement.ip, 'host_node')
            # KB specific: fix of port translations
            serviceAddressPort = snmpRowElement.port
            serviceAddress = modeling.createServiceAddressOsh(
                poolMember, snmpRowElement.ip, serviceAddressPort,
                CNT_PROTOCOL_MAP[snmpRowElement.protocol])

            self.OSHVResult.add(poolMember)

            if svcToCntMap.has_key(snmpRowElement.svc_name):
                cntList = svcToCntMap[snmpRowElement.svc_name]
                for cnt in cntList:
                    # KB specific: if there is not any port translation between the input and output IPs ports, create the same port
                    destinationPort = serviceAddressPort
                    destinationAddress = serviceAddress
                    if destinationPort == '0':
                        inputServiceAddress = self.resourcePoolsToServiceAddress[
                            cnt.getAttributeValue('data_name')]
                        destinationPort = inputServiceAddress.getAttributeValue(
                            'ipport_number')
                        destinationAddress = modeling.createServiceAddressOsh(
                            poolMember, snmpRowElement.ip, destinationPort,
                            CNT_PROTOCOL_MAP[snmpRowElement.protocol])
                        self.OSHVResult.add(destinationAddress)

                    self.OSHVResult.add(
                        modeling.createLinkOSH('member', cnt,
                                               destinationAddress))
            else:
                self.OSHVResult.add(serviceAddress)
                errobj = errorobject.createError(
                    errorcodes.NO_SERVICE_FOUND_FOR_NODE,
                    [snmpRowElement.svc_name],
                    'No service found for destination node')
                logger.reportWarningObject(errobj)
示例#28
0
def build_network_device(device):
    '''
    Build Layer 2 connection end.
    @type param: NetworkDevice -> OSH
    '''
    device_osh = None
    device_ip_address_osh = None
    device_interface_osh = None
    device_member_ip = None
    if device.ucmdb_id:
        device_osh = modeling.createOshByCmdbIdString('node', device.ucmdb_id)
    if device.mac_address:
        if not device_osh:
            device_osh = modeling.createCompleteHostOSH('node', device.mac_address)
        device_interface_osh = modeling.createInterfaceOSH(device.mac_address, device_osh)
    if device.ip_address:
        if not device_osh:
            device_osh = modeling.createHostOSH(device.ip_address)
        device_ip_address_osh = modeling.createIpOSH(device.ip_address)
        device_member_ip = modeling.createLinkOSH('contained', device_osh, device_ip_address_osh)
    if device.port:
        if device_interface_osh:
            device_interface_osh.setAttribute('interface_name', device.port)
        elif device_osh:
            device_interface_osh = ObjectStateHolder('interface')
            device_interface_osh.setContainer(device_osh)
            device_interface_osh.setAttribute('interface_name', device.port)
    return device_osh, device_ip_address_osh, device_interface_osh, device_member_ip
示例#29
0
	def discoverContentRules(self):
		contentRuleQueryBuilder = SnmpQueryBuilder(CNT_OID_OFFSET)
		contentRuleQueryBuilder.addQueryElement(2, 'cnt_name')
		contentRuleQueryBuilder.addQueryElement(4, 'ipserver_address')
		contentRuleQueryBuilder.addQueryElement(5, 'ipport_type')
		contentRuleQueryBuilder.addQueryElement(6, 'ipport_number')
		contentRuleQueryBuilder.addQueryElement(68, 'ip_range')
		snmpRowElements = self.snmpAgent.getSnmpData(contentRuleQueryBuilder)
		
		for snmpRowElement in snmpRowElements:
			virtualServer = modeling.createHostOSH(snmpRowElement.ipserver_address, 'clusteredservice')
			virtualServerHostKey = virtualServer.getAttributeValue('host_key')
			virtualServer.setAttribute('data_name', virtualServerHostKey)
			self.OSHVResult.add(modeling.createLinkOSH('owner', self.css, virtualServer))
			self.OSHVResult.add(virtualServer)			
			
			resourcePool = ObjectStateHolder('loadbalancecluster')
			resourcePool.setStringAttribute('data_name', snmpRowElement.cnt_name)
			self.OSHVResult.add(modeling.createLinkOSH('contained', resourcePool, virtualServer))
			self.OSHVResult.add(resourcePool)
			self.resourcePools[snmpRowElement.cnt_name] = resourcePool
			
			serviceAddress = modeling.createServiceAddressOsh(virtualServer,
											snmpRowElement.ipserver_address,
											snmpRowElement.ipport_number,
											CNT_PROTOCOL_MAP[snmpRowElement.ipport_type])
			serviceAddress.setContainer(virtualServer)
			self.OSHVResult.add(serviceAddress)

			# KB specific: fix of port translations
			self.resourcePoolsToServiceAddress[snmpRowElement.cnt_name] = serviceAddress

			for i in range(int(snmpRowElement.ip_range)):
				#TODO: Add all IPs from range
				pass
示例#30
0
def osh_createiSeriesOsh(defaultIp, model, osversion, serialnbr, sysname,
                         macAddress):

    # Create Iseries OSH ----------------------------------
    str_discovered_os_name = 'discovered_os_name'
    str_discovered_os_version = 'discovered_os_version'
    str_discovered_os_vendor = 'discovered_os_vendor'
    str_discovered_model = 'discovered_model'
    str_vendor = 'vendor'
    str_os_vendor = 'os_vendor'
    str_name = 'name'
    host_key = 'host_key'
    str_serialnbr = 'serial_number'

    isComplete = 1
    os400Osh = modeling.createHostOSH(defaultIp, 'as400_node', _STR_EMPTY,
                                      _STR_EMPTY, _STR_EMPTY)
    os400Osh.setAttribute(str_discovered_os_name, 'os/400')
    os400Osh.setBoolAttribute('host_iscomplete', isComplete)
    os400Osh.setAttribute(str_discovered_os_version, osversion)
    os400Osh.setAttribute(str_discovered_model, model)
    os400Osh.setAttribute(str_os_vendor, 'IBM')
    os400Osh.setAttribute(str_discovered_os_vendor, 'IBM')
    os400Osh.setAttribute(str_vendor, 'IBM')
    os400Osh.setAttribute(str_name, sysname)
    os400Osh.setAttribute(str_serialnbr, serialnbr)
    os400Osh.setAttribute(host_key, macAddress)

    return os400Osh
示例#31
0
def createShellObj(shell,
                   client,
                   ip,
                   langBund,
                   language,
                   codePage,
                   arpMac=None,
                   connectedShellCredId=None):
    'Shell, str, langBundle, str, str -> osh'
    # make sure that 'ip' is an ip and not a dns name
    # the reason is to make application_ip attribute hold an ip and not a dns name,
    # hence, when the application will be a trigger it will find the probe
    clientType = shell.getClientType()
    if clientType == ClientsConsts.NTCMD_PROTOCOL_NAME:
        clientType = "ntcmd"
    logger.debug('creating object for obj_name=%s' % clientType)

    ipObj = ip
    if ip_addr.isValidIpAddress(ip):
        ipObj = ip_addr.IPAddress(ip)
    else:
        # maybe it's a hostname?
        hostname = ip
        try:
            ips = SocketDnsResolver().resolve_ips(hostname)
            ipObj = ips[0]
        except ResolveException:
            logger.reportWarning('Could not resolve hostname' + hostname)
            ipObj = ip

    shellOsh = ObjectStateHolder(clientType)

    shellOsh.setAttribute('application_ip', str(ipObj))
    shellOsh.setAttribute('data_name', clientType)

    if clientType != "ntcmd":
        shellOsh.setAttribute('application_port', shell.getPort())
        shellOsh.setContainer(modeling.createHostOSH(str(ipObj)))

    # UDA client has a property of version, it should be reported
    if clientType == ClientsConsts.DDM_AGENT_PROTOCOL_NAME:
        shellOsh.setAttribute('version', client.getVersion())

    if (language):
        shellOsh.setAttribute('language', language)
    if (codePage):
        shellOsh.setAttribute('codepage', codePage)

    shellOsh.setAttribute('credentials_id', shell.getCredentialId())

    if arpMac:
        shellOsh.setAttribute(TopologyConstants.ATTR_APPLICATION_ARP_MAC,
                              arpMac)

    if connectedShellCredId:
        shellOsh.setAttribute(TopologyConstants.ATTR_CONN_OS_CRED_ID,
                              connectedShellCredId)

    return shellOsh
示例#32
0
def DiscoveryMain(Framework):
    ip = Framework.getTriggerCIData('ip_address')
    credentialIds = netutils.getAvailableProtocols(Framework, 'ucs', ip)
    if not credentialIds:
        logger.warn('No generic credential for UCS')
        Framework.reportWarning('No generic credential for UCS')
        return

    ucs_id = Framework.getTriggerCIData('ucs_id')

    originFramework = Framework
    connectionManager = None
    connectedCredentialId = None
    for credentialId in credentialIds:
        logger.debug('Begin trying credential id:', credentialId)
        params = {'credentialsId': credentialId}
        tmpFramework = MyFramework(originFramework, parameters=params)
        manager = FrameworkBasedConnectionDataManager(tmpFramework, ip)
        try:
            client = manager.getClient()
            if client:
                logger.debug("Connected")
                connectionManager = manager
                connectedCredentialId = credentialId
                break
        except:
            logger.debugException('')
            logger.debug('Can not connection by credential:', credentialId)
        finally:
            if connectionManager:
                connectionManager.closeClient()

    if connectionManager:
        logger.debug('Connected by credential Id:', connectedCredentialId)
        vec = ObjectStateHolderVector()
        hostOsh = modeling.createHostOSH(ip)
        appOsh = modeling.createApplicationOSH('running_software',
                                               'UCS',
                                               hostOsh,
                                               vendor='Cisco')
        appOsh.setAttribute('application_ip', ip)
        appOsh.setAttribute('credentials_id', connectedCredentialId)
        vec.add(hostOsh)
        vec.add(appOsh)
        return vec
    else:
        if ucs_id:
            logger.debug('Delete the ucs since it can not be connected:%s' %
                         ucs_id)
            softwareOsh = modeling.createOshByCmdbId('running_software',
                                                     ucs_id)
            Framework.deleteObject(softwareOsh)

        logger.warn(
            'All credentials have been tried. No credential can connect to UCS by ip %s'
            % ip)
        Framework.reportWarning(
            'All credentials have been tried. No credential can connect to UCS by ip %s'
            % ip)
示例#33
0
def DiscoveryMain(Framework):
    properties = Properties()
    vector = ObjectStateHolderVector()
    properties.setProperty('timeoutDiscover',
                           Framework.getParameter('timeoutDiscover'))
    properties.setProperty('retryDiscover',
                           Framework.getParameter('retryDiscover'))
    properties.setProperty('pingProtocol',
                           Framework.getParameter('pingProtocol'))
    properties.setProperty('threadPoolSize',
                           Framework.getParameter('threadPoolSize'))
    ip = Framework.getDestinationAttribute('ip_address')
    domainName = Framework.getDestinationAttribute('domain_name')
    id = Framework.getTriggerCIData('id')
    ports = getUDAAvailablePorts(Framework)

    try:
        client = Framework.createClient(ClientsConsts.ICMP_PROTOCOL_NAME,
                                        properties)
        try:
            range_uda_status = {}
            range_result = pingIPsInRange(Framework, client, ip, ports)
            range_uda_status.update(range_result)

            for x in range_uda_status.values():
                logger.debug(x)
                #build the udaStatus
                context = UdaState.Builder(x.ip).computerName(
                    x.computerName
                ).alive(x.alive).portAlive(x.portAlive).isDDMI(
                    x.isDDMI).isNative(x.isNative).isWin(x.isWin).osType(
                        x.osType).agentVersion(
                            str(x.agentVersion) +
                            ('-fips' if x.isFIPSEnabled else '')).UDUniqueId(
                                x.UDUniqueId).build()
                #save
                UdaStatusService.getInstance().saveUdaStatus(context)
                if Framework.getParameter('isCreateUDA') == 'true':
                    if x.UDUniqueId:
                        hostOsh = modeling.createHostOSH(x.ip)
                        hostOsh.setStringAttribute(
                            InventoryUtils.ATTR_UD_UNIQUE_ID, x.UDUniqueId)
                        uda = ObjectStateHolder('uda')
                        uda.setStringAttribute('application_ip', x.ip)
                        uda.setStringAttribute('application_ip_domain',
                                               domainName)
                        uda.setStringAttribute('discovered_product_name',
                                               'uda')
                        uda.setStringAttribute('version', str(x.agentVersion))
                        uda.setContainer(hostOsh)
                        vector.add(hostOsh)
                        vector.add(uda)
        finally:
            client.close()
    except:
        msg = logger.prepareJythonStackTrace('')
        errormessages.resolveAndReport(msg, ClientsConsts.ICMP_PROTOCOL_NAME,
                                       Framework)
    return vector
示例#34
0
    def getTopology(self, ipAddress):
        lb = modeling.createHostOSH(ipAddress, 'host')
        cisco_ace = modeling.createApplicationOSH('cisco_ace', 'Cisco_ACE', lb,
                                                  'Load Balance', 'Cisco')
        self.OSHVResult.add(lb)
        self.OSHVResult.add(cisco_ace)

        self.discoverVirtualServers(cisco_ace)
示例#35
0
 def getTopology(self, ipAddress):
     #TODO change host to lb
     lb = modeling.createHostOSH(ipAddress, 'host')
     f5 = modeling.createApplicationOSH('f5_ltm', 'F5 BIG-IP LTM', lb)
     self.add(lb)
     self.add(f5)        
     
     self.discoverF5(f5)
示例#36
0
 def createDbOsh(self, dbsid, dbport, ipaddress):
     hostOsh = modeling.createHostOSH(ipaddress)
     mysqlOsh = modeling.createDatabaseOSH('mysql', dbsid, dbport,
                                           ipaddress, hostOsh)
     if not mysqlOsh.getAttribute('application_version'):
         mysql_version_by_shell.setVersion(mysqlOsh, self.processPath,
                                           self.shell)
     return mysqlOsh, hostOsh
示例#37
0
def executeWmiQuery(client, OSHVResult, nodeOsh = None):
    containerOsh = nodeOsh or modeling.createHostOSH(client.getIpAddress()) 
    wmiProvider = wmiutils.WmiAgentProvider(client) 
    shareDiscoverer = hostresource_win_wmi.FileSystemResourceDiscoverer(wmiProvider)
    sharedResources = shareDiscoverer.getSharedResources()
    for sharedResource in sharedResources:
        createSharedResourceOsh(sharedResource, containerOsh, OSHVResult)
    logger.debug("Discovered ", len(sharedResources), " shares")
示例#38
0
 def build(self):
     if self.ipAddress and self.queueName:
         self.hostOsh = modeling.createHostOSH(self.ipAddress)
         self.msMqManagerOsh = modeling.createApplicationOSH(
             'msmqmanager', 'Microsoft MQ Manager', self.hostOsh)
         self.queueOsh = ObjectStateHolder('msmqqueue')
         self.queueOsh.setAttribute('data_name', self.queueName.lower())
         self.queueOsh.setContainer(self.msMqManagerOsh)
示例#39
0
 def reportConsolidators(self, hostList):
     for hostName in hostList:
         ip = resolveHostIp(hostName)
         if ip:
             hostOsh = modeling.createHostOSH(ip)
             consolidatorOsh = self.createConsolidatorForHost(APP_SCOM_SERVER_NAME, hostOsh)
             self.resultsVector.add(consolidatorOsh)
             self.resultsVector.add(hostOsh)
 def build_osh(self):
     if self.__ips:
         # TODO deal with createHostOSH for multiple IPs
         node_ip_object = self.__ips[0]
         logger.debug('nodeName: ', self.__name, ' node_ip_object: ', node_ip_object)
         return modeling.createHostOSH(str(node_ip_object))
     else:
         raise Exception("Can't report node '%s' due to unresolved ip" % self.__name)
示例#41
0
 def buildDhcpServers(self):
     if self.dhcpServerIpList:
         for dhcpIpAddr in self.dhcpServerIpList:
             if ip_addr.isValidIpAddress(dhcpIpAddr, filter_client_ip=True):
                 dhcpHostOsh = modeling.createHostOSH(str(dhcpIpAddr))
                 dhcpAppOsh = modeling.createDhcpOsh(str(dhcpIpAddr), dhcpHostOsh)
                 self.resultVector.add(dhcpHostOsh)
                 self.resultVector.add(dhcpAppOsh)
示例#42
0
 def buildWinsServers(self):
     if self.winsServerIpList:
         for winsIpAddr in self.winsServerIpList:
             if ip_addr.isValidIpAddress(winsIpAddr, filter_client_ip=True):
                 winsHostOsh = modeling.createHostOSH(str(winsIpAddr))
                 winsAppOsh = modeling.createWinsOsh(str(winsIpAddr), winsHostOsh)
                 self.resultVector.add(winsHostOsh)
                 self.resultVector.add(winsAppOsh)
示例#43
0
    def report(self, oshVector, interaction):
        srcNode, dstNode = interaction.srcNode, interaction.dstNode
        if self.acceptorEngine.accepts(srcNode):
            srcNode.ipOsh = modeling.createIpOSH(srcNode.ip)
            srcNode.hostOsh = modeling.createHostOSH(srcNode.ip)
            srcContainedLink = modeling.createLinkOSH('contained', srcNode.hostOsh, srcNode.ipOsh)
            oshVector.add(srcNode.ipOsh)
            oshVector.add(srcNode.hostOsh)
            oshVector.add(srcContainedLink)

        if self.acceptorEngine.accepts(dstNode):
            dstNode.ipOsh = modeling.createIpOSH(dstNode.ip)
            dstNode.hostOsh = modeling.createHostOSH(dstNode.ip)
            dstContainedLink = modeling.createLinkOSH('contained', dstNode.hostOsh, dstNode.ipOsh)
            oshVector.add(dstNode.ipOsh)
            oshVector.add(dstNode.hostOsh)
            oshVector.add(dstContainedLink)
示例#44
0
def executeWmiQuery(client, OSHVResult, nodeOsh=None):
    '''
    @deprecated: Use NTCMD_HR_Dis_Disk_Lib.discoverDiskByWmic instead
    '''
    containerOsh = nodeOsh or modeling.createHostOSH(client.getIpAddress())
    NTCMD_HR_Dis_Disk_Lib.discoverDiskByWmic(client, OSHVResult, containerOsh)
    NTCMD_HR_Dis_Disk_Lib.discoverPhysicalDiskByWmi(client, OSHVResult,
                                                    containerOsh)
示例#45
0
    def handleMsClusteredInstance(self, context, applicationOsh):
        if context.client.getClientType() == ClientsConsts.WMI_PROTOCOL_NAME:
            return
        msClusterHandler = MssqlMsClusterHandler(context)
        if msClusterHandler.isClustered():

            msSqlName = applicationOsh.getAttribute(
                'database_dbsid').getValue()
            splitedName = msSqlName.split('\\')

            hostName = None
            instanceName = None

            if len(splitedName) > 1:
                hostName = splitedName[0]
                instanceName = splitedName[1]
            else:
                instanceName = msSqlName

            #if there's no instance name nothing to process
            if not instanceName:
                return
            #fetching related to sql server resource group
            resourceGroup = msClusterHandler.getMsSqlRelatedClusterGroup(
                instanceName)
            logger.debug('Found resource group %s' % resourceGroup)
            #checking if the resource group related to the sql server instance.
            isMsSqlInstanceRelatedGroup = msClusterHandler.isMsSqlInstanceRelatedClusterGroup(
                resourceGroup, instanceName)
            if not isMsSqlInstanceRelatedGroup:
                logger.debug('%s is not related to ms sql server instance %s' %
                             (resourceGroup, instanceName))
                return
            #fetching related ip resources
            clusterResources = resourceGroup and msClusterHandler.getClusterIpResources(
                resourceGroup)
            logger.debug('Found resources %s' % clusterResources)
            if clusterResources:
                for clusterResource in clusterResources:
                    pairs = msClusterHandler.getClusterResourceNameAndIps(
                        clusterResource)
                    logger.debug('Discovered pairs %s' % pairs)
                    if pairs:
                        for pair in pairs:
                            if len(pair) > 1:
                                logger.debug(
                                    'Reporting database host %s instance %s' %
                                    (pair[0].upper(), instanceName))
                                if pair[0].upper() != instanceName.upper():
                                    applicationOsh.setStringAttribute(
                                        'database_dbsid', '%s\\%s' %
                                        (pair[0].upper(), instanceName))
                                else:
                                    applicationOsh.setStringAttribute(
                                        'database_dbsid', instanceName)
                                hostOsh = modeling.createHostOSH(str(pair[1]))
                                applicationOsh.setContainer(hostOsh)
                                return
示例#46
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    snmpMethod = getFrameworkParameter(Framework, 'snmpMethod', SnmpQueries.defaultSnmpMethod)
    backupSnmpMethod = getFrameworkParameter(Framework, 'backupSnmpMethod', SnmpQueries.defaultBackupSnmpMethod)
    moonWalkBulkSize = int(getFrameworkParameter(Framework, 'moonWalkBulkSize', SnmpQueries.defaultMoonWalkBulkSize))
    moonWalkSleep = long(getFrameworkParameter(Framework, 'moonWalkSleep', SnmpQueries.defaultMoonWalkSleep))
    snmpBulkSize = int(getFrameworkParameter(Framework, 'snmpBulkSize', SnmpQueries.defaultSnmpBulkSize))
    discoverUnknownIPs = Boolean.parseBoolean(Framework.getParameter('discoverUnknownIPs'))
    
    #getting DestinationData from Framework; the method is protected.
    destination = Framework.getCurrentDestination()
    
    discoveredHostIpList = SnmpQueries.getSnmpIpDataOneDestination(snmpMethod, snmpBulkSize, moonWalkBulkSize, moonWalkSleep, Boolean.FALSE, destination)
    logger.debug('Discover ARP by %s returned %s objects' % (snmpMethod, str(discoveredHostIpList.size())))
    if (discoveredHostIpList.size() == 0) and (snmpMethod != backupSnmpMethod):
        discoveredHostIpList = SnmpQueries.getSnmpIpDataOneDestination(backupSnmpMethod, snmpBulkSize, moonWalkBulkSize, moonWalkSleep, Boolean.FALSE, destination)
        logger.debug('Discover ARP by %s returned %s objects' % (backupSnmpMethod, str(discoveredHostIpList.size())))
        if (discoveredHostIpList.size()==0):
            Framework.reportWarning('Failed to discover SNMP IP data')
            return OSHVResult
    
    discoveredHostArpList = SnmpQueries.getSnmpArpDataOneDestination(snmpMethod, snmpBulkSize, moonWalkBulkSize, moonWalkSleep, Boolean.FALSE, destination)
    discoveredHostArpList.addAll(SnmpQueries.getSnmpArpDataOneDestination(snmpMethod, snmpBulkSize, moonWalkBulkSize, moonWalkSleep, Boolean.FALSE, Boolean.TRUE, destination))
    if (discoveredHostArpList.size()==0) and (snmpMethod != backupSnmpMethod):
        discoveredHostArpList = SnmpQueries.getSnmpArpDataOneDestination(backupSnmpMethod, snmpBulkSize, moonWalkBulkSize, moonWalkSleep, Boolean.FALSE, destination)
        discoveredHostArpList.addAll(SnmpQueries.getSnmpArpDataOneDestination(backupSnmpMethod, snmpBulkSize, moonWalkBulkSize, moonWalkSleep, Boolean.FALSE, Boolean.TRUE, destination))
        if (discoveredHostArpList.size()==0):
            Framework.reportWarning('Failed to discover SNMP ARP data')
            return OSHVResult

    networkOSH = None
    for i in range(discoveredHostArpList.size()):
        currArp = discoveredHostArpList.get(i)
        for currIp in discoveredHostIpList:
            if networkOSH is None:
                networkOSH = modeling.createNetworkOSH(currIp.netaddr, currIp.netmask)
                OSHVResult.add(networkOSH)
            if (currIp.domain == 'unknown') and not discoverUnknownIPs:
                continue
            if not netutils.isValidMac(currArp.designatedMacAddress):
                continue
            
            #report start
            designatedIpNetAddress = IPv4(currArp.designatedIpAddress, currIp.netmask).getFirstIp().toString();
            if designatedIpNetAddress == currIp.netaddr:
                hostOSH = modeling.createHostOSH(currArp.designatedIpAddress)
                OSHVResult.add(hostOSH)
                OSHVResult.add(modeling.createLinkOSH('member', networkOSH, hostOSH))
                
                ipOsh = modeling.createIpOSH(currArp.designatedIpAddress, currIp.netmask)
                OSHVResult.add(ipOsh)
                OSHVResult.add(modeling.createLinkOSH('member', networkOSH, ipOsh))
                
                ifOsh = modeling.createInterfaceOSH(netutils.parseMac(currArp.designatedMacAddress), hostOSH)
                OSHVResult.add(ifOsh)
                OSHVResult.add(modeling.createLinkOSH('containment', ifOsh, ipOsh))
    
    return OSHVResult
示例#47
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    shell = None
    defOraHomes = Framework.getParameter('OracleHomes')
    hostPrimaryIP = Framework.getDestinationAttribute('ip_address')
    protocol = Framework.getDestinationAttribute('Protocol')
    listenerNames = Framework.getTriggerCIDataAsList('listener_names')
    listenerPaths = Framework.getTriggerCIDataAsList('listener_process_path')
    errorMessage = None
    try:
        client = Framework.createClient()
        try:
            shell = shellutils.ShellUtils(client)
            
            hostOSH = modeling.createHostOSH(hostPrimaryIP)
            OSHVResult.add(hostOSH)
            if len(listenerPaths) < len(listenerNames):
                path = listenerPaths[0]
                for i in range(len(listenerNames) - len(listenerPaths)):
                    listenerPaths.append(path)

            for i in range(len(listenerPaths)):
                try:
                    listenerPath = listenerPaths[i]
                    listenerName = listenerNames[i]
                    
                    listenerConf = ListenerConfiguration(shell, listenerName, listenerPath, defOraHomes)
                    listenerConf.discover()
                    
                    listenedIPs = listenerConf.getListenedIPsAsString()
                    
                    resolver = DNSResolver(shell, None, hostPrimaryIP)
                    ipPrim = resolver.resolveIpByHostname()
                    if ipPrim and ipPrim != hostPrimaryIP:
                        hostPrimaryIP = ipPrim
                        resolver = DNSResolver(shell, None, hostPrimaryIP)
                    #for UCMDB 9.x due to new reconsiliation FQDN is not vital            
                    hostDnsName = resolver.getDnsName() or ' '
                    if hostDnsName and listenedIPs:
                        listenedFull = hostDnsName + ':' + hostPrimaryIP + '@' + listenedIPs
                        listenerName = listenerConf.getListenerName()
                        listenerVersion = listenerConf.getVersion()
                        listenerOSH = createListenerOSH(hostOSH, listenedFull, listenerName, listenerVersion)
                        if listenerOSH:
                            OSHVResult.add(listenerOSH)
                    else:
                        Framework.reportWarning('Failed to create listener OSH. Either host name or listened ips are not defined.')
                except:
                    logger.debugException('')
                    Framework.reportWarning('Failed to discover one or more listeners parameters.')
        finally:
            try:
                shell and shell.closeClient()
            except:
                logger.debugException('')
                logger.error('Unable to close shell')
    except JException, ex:
        errorMessage = ex.getMessage()
示例#48
0
 def buildWinsServers(self):
     if self.winsServerIpList:
         for winsIpAddr in self.winsServerIpList:
             if ip_addr.isValidIpAddress(winsIpAddr, filter_client_ip=True):
                 winsHostOsh = modeling.createHostOSH(str(winsIpAddr))
                 winsAppOsh = modeling.createWinsOsh(
                     str(winsIpAddr), winsHostOsh)
                 self.resultVector.add(winsHostOsh)
                 self.resultVector.add(winsAppOsh)
示例#49
0
 def buildDhcpServers(self):
     if self.dhcpServerIpList:
         for dhcpIpAddr in self.dhcpServerIpList:
             if ip_addr.isValidIpAddress(dhcpIpAddr, filter_client_ip=True):
                 dhcpHostOsh = modeling.createHostOSH(str(dhcpIpAddr))
                 dhcpAppOsh = modeling.createDhcpOsh(
                     str(dhcpIpAddr), dhcpHostOsh)
                 self.resultVector.add(dhcpHostOsh)
                 self.resultVector.add(dhcpAppOsh)
示例#50
0
def executeWmiQuery(client, OSHVResult, nodeOsh=None):
    containerOsh = nodeOsh or modeling.createHostOSH(client.getIpAddress())
    wmiProvider = wmiutils.WmiAgentProvider(client)
    shareDiscoverer = hostresource_win_wmi.FileSystemResourceDiscoverer(
        wmiProvider)
    sharedResources = shareDiscoverer.getSharedResources()
    for sharedResource in sharedResources:
        createSharedResourceOsh(sharedResource, containerOsh, OSHVResult)
    logger.debug("Discovered ", len(sharedResources), " shares")
示例#51
0
def createHostOSHwithIP(OSHVResult, ipAddress):
    # create Host and ipAddress CIs and relations
    hostOSH = modeling.createHostOSH(ipAddress)
    ipOSH = modeling.createIpOSH(ipAddress)
    link = modeling.createLinkOSH('containment', hostOSH, ipOSH)
    OSHVResult.add(hostOSH)
    OSHVResult.add(ipOSH)
    OSHVResult.add(link)
    return hostOSH, ipOSH
示例#52
0
def createHostOSHwithIP(OSHVResult, ipAddress):
    # create Host and ipAddress CIs and relations
    hostOSH = modeling.createHostOSH(ipAddress)
    ipOSH = modeling.createIpOSH(ipAddress)
    link = modeling.createLinkOSH('containment', hostOSH, ipOSH)
    OSHVResult.add(hostOSH)
    OSHVResult.add(ipOSH)
    OSHVResult.add(link)
    return hostOSH, ipOSH
示例#53
0
 def reportConsolidators(self, hostList):
     for hostName in hostList:
         ip = resolveHostIp(hostName)
         if ip:
             hostOsh = modeling.createHostOSH(ip)
             consolidatorOsh = self.createConsolidatorForHost(
                 APP_SCOM_SERVER_NAME, hostOsh)
             self.resultsVector.add(consolidatorOsh)
             self.resultsVector.add(hostOsh)
示例#54
0
def doQueryOSUsers(client, OSHVResult):
	_hostObj = modeling.createHostOSH(client.getIpAddress())
	data_name_mib = '1.3.6.1.4.1.77.1.2.25.1.1,1.3.6.1.4.1.77.1.2.25.1.2,string'
	resultSet = client.executeQuery(data_name_mib)#@@CMD_PERMISION snmp protocol execution
	while resultSet.next():
		UserName = resultSet.getString(2)
		########## send object ##############
		OSUserOSH = doOSUserOSH(UserName)
		OSUserOSH.setContainer(_hostObj)
		OSHVResult.add(OSUserOSH)
    def build(self):
        vector = self.newVector()
        backend_server_osh = modeling.createHostOSH(self.service.server.ip)
        vector.add(backend_server_osh)

        realIPServiceOsh = modeling.createServiceAddressOsh(backend_server_osh, self.service.ip, self.service.port,
                                                            modeling.SERVICEADDRESS_TYPE_TCP,
                                                            self.service.service_type)
        vector.add(realIPServiceOsh)
        vector.add(modeling.createLinkOSH('membership', self.lbcOsh, realIPServiceOsh))
        return vector
示例#56
0
 def reportDomainControllers(self, resultsVector):
     if self.domainFqdn:
         resolver = DNSResolver(self.client)
         ipList = resolver.resolveIpByNsLookup(self.domainFqdn)
         for ipAddress in ipList:
             logger.debug("Reporting Domain Controller for ip: " + ipAddress)
             hostOsh = modeling.createHostOSH(ipAddress)
             domainControllerOsh = modeling.createApplicationOSH("domaincontroller", "DomainController", hostOsh)
             modeling.setApplicationProductName(domainControllerOsh, "domain_controller")
             resultsVector.add(hostOsh)
             resultsVector.add(domainControllerOsh)