Example #1
0
def _discoverDatabase(client, baseTopology):
    r'@types: BaseSapJmxClient, BaseTopology -> oshv'
    logger.info("Discover DB information")
    vector = ObjectStateHolderVector()
    try:
        dbInfo = _getDatabase(client)
    except (Exception, JException):
        logger.warnException("Failed to get DB info using new MBean model")
    else:
        if dbInfo:
            try:
                logger.info("Resolve DB address: ", dbInfo.hostname)
                dnsResolver = netutils.JavaDnsResolver()
                ips = dnsResolver.resolveIpsByHostname(dbInfo.hostname)
                hostReporter = sap.HostReporter(sap.HostBuilder())
                hostOsh, hVector = hostReporter.reportHostWithIps(*ips)
                vector.addAll(hVector)
                hVector.clear()
            except netutils.ResolveException:
                logger.warn("DB won't be reported as DB addr is not resolved")
            else:
                try:
                    logger.info("Discovered: ", dbInfo)
                    systemOsh = baseTopology.systemOsh
                    vector.addAll(sap_db.report_db_info(dbInfo, systemOsh, hostOsh))
                except ValueError, ve:
                    logger.warn("%s: %s" % (ve, dbInfo.type))
Example #2
0
def _resolveInstHostname(inst):
    r'@types: sap.Instance -> list[str]'
    dnsResolver = netutils.JavaDnsResolver()
    try:
        return dnsResolver.resolveIpsByHostname(inst.hostname)
    except netutils.ResolveException, re:
        logger.warn("Failed to resolve IPs for %s" % inst.hostname)
Example #3
0
def _resolvedEndpointAddress(endpoint):
    r'@types: Endpoint -> list[Endpoint]'
    if endpoint:
        try:
            resolveAddressFn = netutils.JavaDnsResolver().resolveIpsByHostname
            return sap_discoverer.resolveEndpointAddress(resolveAddressFn,
                                                         endpoint)
        except netutils.ResolveException, re:
            logger.warn("Failed to resolve %s" % endpoint.getAddress())
Example #4
0
def _discoverInstanceDetails(client, baseTopology):
    r'@types: BaseSapJmxClient, str, System, osh, osh -> oshv'
    system, hostname, clusterOSH, systemOsh = baseTopology
    inst, servers = ServerProcessQuery().getSystemDetails(client)
    if not inst.hostname and hostname:
        inst = sap.Instance.replaceHostname(inst, hostname)

    instanceReporter = sap_jee.InstanceReporter(sap_jee.InstanceBuilder())

    # report host by resolved IPs
    hostname = inst.hostname
    if not hostname:
        logger.warn("Failed to determine hostname for %s" % inst)
        return ObjectStateHolderVector()

    dnsResolver = netutils.JavaDnsResolver()
    vector = ObjectStateHolderVector()
    try:
        ips = dnsResolver.resolveIpsByHostname(hostname)
    except netutils.ResolveException:
        logger.warn("Failed to resolve hostname of %s" % inst)
    else:
        hostReporter = sap.HostReporter(sap.HostBuilder())
        hostOSH, vector = hostReporter.reportHostWithIps(*ips)

        # report instance
        pdo = sap_jee.InstanceBuilder.InstancePdo(inst, system)
        instOsh = instanceReporter.reportInstancePdo(pdo, hostOSH)
        vector.add(instOsh)
        #report sap system
        systemOsh.setStringAttribute('data_note', 'This SAP System link to ' + hostOSH.getAttributeValue('host_key'))
        vector.add(systemOsh)

        # report j2ee_cluster -membership-> sap_app_server
        linkReporter = sap.LinkReporter()
        vector.add(linkReporter.reportMembership(clusterOSH, instOsh))
        vector.add(linkReporter.reportMembership(systemOsh, instOsh))

        # report server processes
        oshs = [_reportServerProcess(s, inst, instOsh) for s in servers]
        each(vector.add, oshs)

        # discover applications
        serverToOshs = filter(comp(_isWorkerProcess, first), zip(servers, oshs))
        for server, osh in serverToOshs:
            id_ = server.id
            appNameToOsh = Sf(discoverEjbApplications)(client, id_, osh, clusterOSH, vector)
            Sf(buildWebApplications)(client, id_, osh, clusterOSH, appNameToOsh, vector)
    return vector
Example #5
0
    '''
    platform = jee.Platform.WEBSPHERE
    properties = Properties()
    properties.put('server_was_config', 'services:connectors:SOAP_CONNECTOR_ADDRESS:host,services:connectors:SOAP_CONNECTOR_ADDRESS:port,clusterName')
    properties.put('datasource_was_config', 'jndiName,URL,propertySet,connectionPool')
    try:
        client = Framework.createClient(properties)
    except (Exception, JException), exc:
        logger.warnException("Failed to establish connection")
        jee_connection.reportError(Framework, str(exc), platform.getName())
    else:
        try:
            try:
                provider = jmx.Provider( client )
                dnsResolver = jee_discoverer.DnsResolverDecorator(
                                netutils.JavaDnsResolver(), client.getIpAddress()
                )
                jdbcResourceDiscoveryEnabled = Boolean.valueOf(Framework.getParameter('discoverJDBCResources'))
                jmsResourcesDiscoveryEnabled = Boolean.valueOf(Framework.getParameter('discoverJMSResources'))
                applicationModulesDiscoveryEnabled = Boolean.valueOf(Framework.getParameter('discoverAppResources'))

                namesOfServers = jee_connection.getParameterAsList(Framework, 'servers')
                isAmongServersToDiscover = lambda s, l = namesOfServers: not l or s.getName() in l

                namesOfApps = jee_connection.getParameterAsList(Framework, 'applications')
                isAmongApplicationsToDiscover = lambda a, l = namesOfApps: not l or a.getName() in l

                # create reporters and builders for websphere topology
                globalSettings = GeneralSettingsConfigFile.getInstance()
                enabledJeeEnhancedTopology = globalSettings.getPropertyBooleanValue('enableJeeEnhancedTopology', 0)
                if enabledJeeEnhancedTopology:
Example #6
0
def DiscoveryMain(Framework):
    """
    Retrieving a list of LDAP ports we strive to connect to domain controller in
    member role first. So we have to choose the lowest port number in the list.
    """
    protocolName = "LDAP"

    OSHVResult = ObjectStateHolderVector()

    baseDn = Framework.getParameter('baseDN') or None
    if baseDn == 'NA':
        baseDn = None
    ipAddress = Framework.getDestinationAttribute('ip_address')
    credentialsId = Framework.getDestinationAttribute('credentials_id')
    applicationPort = Framework.getDestinationAttribute("application_port")
    serviceAddressPort = Framework.getDestinationAttribute('port')

    if not applicationPort or applicationPort == 'NA':
        applicationPort = serviceAddressPort

    # build environment and connect
    envBuilder = active_directory_utils.LdapEnvironmentBuilder(applicationPort)
    client = Framework.createClient(credentialsId, envBuilder.build())

    discoverer = oracle_ldap_discoverer.OracleLdapDiscoverer(client, baseDn)

    try:
        probe_client  = Framework.createClient(ClientsConsts.LOCAL_SHELL_PROTOCOL_NAME)
        probe_shell = shellutils.ShellFactory().createShell(probe_client)

        resolver = netutils.FallbackResolver([netutils.JavaDnsResolver(), netutils.DnsResolverByShell(probe_shell)])

        # discover
        servers = discoverer.discover()

        # report
        endpoint_builder = netutils.ServiceEndpointBuilder()
        endpoint_reporter = netutils.EndpointReporter(endpoint_builder)

        oracle_builder = db_builder.Oracle()
        reporter = db.OracleTopologyReporter(oracle_builder, endpoint_reporter)

        for dbServer in servers:
            if dbServer:
                try:
                    address = dbServer.address
                    if not ip_addr.isValidIpAddress(address):
                        ips = resolver.resolveIpsByHostname(address)
                        if ips and len(ips) > 0:
                            dbServer.address = str(ip_addr.IPAddress(ips[0]))
                    # get Host OSH
                    if not (dbServer.address
                            and netutils.isValidIp(address)
                            and not netutils.isLocalIp(address)):
                        raise ValueError("Address for the specified server is not valid or is local")
                    hostOsh = modeling.createHostOSH(dbServer.address)

                    # report database
                    OSHVResult.addAll(reporter.reportServerAndDatabases(dbServer, hostOsh))

                    # report TNS Listener
                    listener = db.OracleListener(dbServer.address, dbServer.getPort())
                    OSHVResult.addAll(reporter.reportTnsListener(listener, hostOsh))

                    # report Oracle Service Names
                    if dbServer.getServiceNames():
                        OSHVResult.addAll(reporter.reportServiceNameTopology(dbServer.getServiceNames(), listener.getOsh(), dbServer.getOsh()))

                except netutils.ResolveException:
                    logger.error("Cannot resolve " + dbServer.address + ". Skip")
    except oracle_ldap_discoverer.OracleContextDiscoveryException, ex:
        msg = str(ex)
        logger.debugException(msg)
        logger.error(msg)
Example #7
0
def DiscoveryMain(Framework):
    OshvResult = ObjectStateHolderVector()
    hostOsh = None

    ## Destination data
    hostId = Framework.getDestinationAttribute('hostId') or None
    processRootId = Framework.getDestinationAttribute('processRootId') or None
    processPath = Framework.getDestinationAttribute('processPath') or None
    processCmdLine = Framework.getDestinationAttribute('processCmdLine') or None
    protocol = Framework.getDestinationAttribute('Protocol')
    ipAddress = Framework.getDestinationAttribute('ip_address')
    raw_paths = Framework.getParameter('emsadmin_tool_absolute_paths') or ''
    default_paths = [x.strip() for x in raw_paths.split(',')]
    ## Pattern parameters
    isJmsQueueDiscoveryEnabled = Boolean.valueOf(Framework.getParameter('discover_queues'))
    isJmsTopicDiscoveryEnabled = Boolean.valueOf(Framework.getParameter('discover_topics'))

    ## Container HOST OSH
    if hostId:
        hostOsh = modeling.createOshByCmdbIdString('host', hostId.strip())
        OshvResult.add(hostOsh)
        logger.debug('[' + __name__ + ':DiscoveryMain] Got HOSTID <%s>' % hostId)

    ## EMS OSH
    if processRootId:
        processOsh = modeling.createOshByCmdbIdString('process', processRootId.strip())
        OshvResult.add(processOsh)
        logger.debug('[' + __name__ + ':DiscoveryMain] Got Process ID <%s>' % processRootId)
    else:
        errMsg = "Invalid Tibco EMS Server CI ID received from server. This EMS server will not be processed"
        logger.error(errMsg)
        logger.reportError(errMsg)
        return OshvResult

    emsTopology = []
    # Attempt to create a shell client
    try:
        client = Framework.createClient()
        shell = shellutils.ShellFactory().createShell(client)
        fallbackDnsResolver = tibco_discoverer.FallbackResolver([netutils.JavaDnsResolver(), netutils.DnsResolverByShell(shell)])
        dnsResolver = tibco_discoverer.CachedResolver(fallbackDnsResolver)

        fs = file_system.createFileSystem(shell)
        emsShellDiscoverer = tibco_discoverer.EmsDiscovererByShell(shell, fs)

        pathUtils = file_system.getPath(fs)
        emsPath = "%s/" % pathUtils.dirName(processPath)
        default_paths.insert(0, emsPath)
        # find out whether emsadmin tool exists and config path present in command line
        for ems_path in default_paths:
            configPath = emsShellDiscoverer.discoverConfigPath(ems_path, processCmdLine)
            if configPath:
                emsPath = ems_path
                logger.debug('Found ems admin utility path %s' % emsPath)
                logger.debug('Found ems config file path %s' % configPath)
                break
        if not emsPath:
            raise ValueError('Failed to discover ems admin utility path. No discovery possible.')
        listenUrls = emsShellDiscoverer.getListenUrls(configPath)
        credList = Framework.getAvailableProtocols(ipAddress, tibco.TIBCO_PROTOCOL)
        # Check if exists any credentials for TIBCO
        if credList:
            for cred in credList:
                for listenUrl in listenUrls:
                    try:
                        emsAdminCommand = tibco_discoverer.EmsAdminCommand(client, cred, emsPath, listenUrl)
                        if testConnection(emsAdminCommand):
                            emsDiscoverer = tibco_discoverer.EmsDiscovererByAdminCommand(emsAdminCommand)
                            emsServer = emsDiscoverer.getEmsServerInfo()
                            jmsServer = emsDiscoverer.extractJmsServerInfoFromUrl(listenUrl)

                            if jmsServer:
                                hostname = jmsServer.hostname
                                try:
                                    ip = dnsResolver.resolveIpsByHostname(hostname)
                                    jmsServer.hostname = netutils.getLowestIp(ip)
                                except:
                                    logger.debug("Cannot resolve %s host" % hostname)
                            if emsServer:
                                emsQueues = isJmsQueueDiscoveryEnabled and emsDiscoverer.getQueues()
                                emsTopics = isJmsTopicDiscoveryEnabled and emsDiscoverer.getTopics()
                            destinations = []
                            if emsQueues or emsTopics:
                                emsQueues and destinations.extend(emsQueues)
                                emsTopics and destinations.extend(emsTopics)
                            emsDataItem = tibco_discoverer.EmsTopology(emsServer, jmsServer, destinations)
                            emsTopology.append(emsDataItem)
                    except tibco_discoverer.TibcoDiscovererException, ex:
                        reportError(str(ex), tibco.TIBCO_PROTOCOL, Framework)
                    except Exception, ex:
                        reportError(str(ex), protocol, Framework)
                    except JException, ex:
                        msg = ex.getMessage()
                        logger.debugException(msg)
                        errormessages.resolveAndReport(msg, protocol, Framework)
Example #8
0
    def getJdbcResources(self, env, jdbcOshMap, globalJdbcResources=None):
        if env is None:
            return
        jdbcResources = HashMap()

        resources = env.getChildren('Resource')
        for resource in resources:
            name = resource.getAttributeValue('name')
            dsType = resource.getAttributeValue('type')
            driverClassName = resource.getAttributeValue('driverClassName')
            url = resource.getAttributeValue('url')
            maxActive = resource.getAttributeValue('maxActive')
            logger.debug('Found jdbc datasource ', name, ' driver ',
                         str(driverClassName), ' url ', str(url))
            jdbcResources.put(
                name,
                JdbcResource(name, dsType, driverClassName, url, maxActive))

        for resource in resources:
            name = resource.getAttributeValue('name')
            if name is None:
                continue
            # do not read additional parameters for non-existing resource
            jdbcResource = jdbcResources.get(name)
            if jdbcResource is None:
                continue

            # update existing JDBC resource with absent parameters data
            for resourceParamsEl in env.getChildren('ResourceParams'):
                if resourceParamsEl.getAttributeValue('name') == name:

                    resourceParams = self.getResourceParamsValues(
                        resourceParamsEl)
                    dsType = resourceParams.get('type')
                    if (dsType is not None) and (jdbcResource.type is None):
                        jdbcResource.type = dsType

                    driverClassName = resourceParams.get('driverClassName')
                    if (driverClassName is not None) and (
                            jdbcResource.driverClass is None):
                        jdbcResource.driverClass = driverClassName

                    url = resourceParams.get('url')
                    if (url is not None) and (jdbcResource.url is None):
                        jdbcResource.url = url

                    maxActive = resourceParams.get('maxActive')
                    if (maxActive
                            is not None) and (jdbcResource.maxActive is None):
                        jdbcResource.maxActive = maxActive

                    if jdbcResource.type != 'javax.sql.DataSource':
                        jdbcResources.remove(name)

        resources = env.getChildren('ResourceLink')
        for resource in resources:
            name = resource.getAttributeValue('name')
            globalName = resource.getAttributeValue('global')
            dsType = resource.getAttributeValue('type')
            logger.debug('Found resource link ', name, ' for global name ',
                         globalName, ' of type ', dsType)
            if dsType != 'javax.sql.DataSource':
                continue
            if globalJdbcResources is not None:
                jdbcResource = globalJdbcResources.get(globalName)
            if jdbcResource is None:
                continue
            logger.debug('Found jdbc datastore with global name ', globalName)
            jdbcOshMap.put(name, jdbcResource)

        dnsResolver = _DnsResolverDecorator(netutils.JavaDnsResolver(),
                                            self.destinationIp)
        reporter = jdbcModule.DnsEnabledJdbcTopologyReporter(
            jdbcModule.DataSourceBuilder(), dnsResolver)

        class Container:
            def __init__(self, osh):
                self.osh = osh

            def getOsh(self):
                return self.osh

        container = Container(self.tomcatOsh)
        for jdbc in jdbcResources.values():
            datasource = jdbcModule.Datasource(jdbc.name,
                                               jdbc.url,
                                               driverClass=jdbc.driverClass)
            self.OSHVResult.addAll(
                reporter.reportDatasources(container, datasource))
            jdbcOshMap.put(jdbc.name, datasource.getOsh())
Example #9
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    client = None
    hostOsh = None
    shell = None

    ## Destination data
    hostId = Framework.getDestinationAttribute('hostId') or None
    bwId = Framework.getDestinationAttribute('bwId') or None
    bwPath = Framework.getDestinationAttribute('bwPath') or None
    protocol = Framework.getDestinationAttribute('Protocol')
    ip_address = Framework.getDestinationAttribute('ip_address')
    tmpDirPath = Framework.getParameter('temp_directory') or '/tmp'
    isDiscoverJms = Framework.getParameter('discover_jms_topology') or "true"
    isDiscoverJms = Boolean.valueOf(isDiscoverJms)

    ## Container HOST OSH
    if hostId:
        hostOsh = modeling.createOshByCmdbIdString('node', hostId.strip())
        OSHVResult.add(hostOsh)
        logger.debug('[' + __name__ +
                     ':DiscoveryMain] Got HOSTID <%s>' % hostId)

    ## Pre-discovered Business Works CI
    bwOsh = None
    if bwId:
        bwOsh = modeling.createOshByCmdbIdString('tibco_business_works',
                                                 bwId.strip())
        logger.debug('[' + __name__ + ':DiscoveryMain] Got bwId <%s>' % bwId)
    else:
        errMsg = '[' + __name__ + ':DiscoveryMain] Invalid TibcoBusinessWorks CI ID received from server. This BW will not be processed'
        logger.error(errMsg)
        logger.reportError(errMsg)
        return OSHVResult

    if not tmpDirPath:
        errMsg = '[' + __name__ + ':DiscoveryMain] temp_directory parameter has not been set correctly. Discovery cannot continue until this parameter is set with a remote directory with write permissions.'
        logger.error(errMsg)
        logger.reportError(errMsg)
        return OSHVResult

    try:
        try:
            client = Framework.createClient()
            shell = shellutils.ShellFactory().createShell(client)
            credList = Framework.getAvailableProtocols(ip_address,
                                                       tibco.TIBCO_PROTOCOL)
            logger.info("Found tibco credentials: %s" % len(credList))

            fs = tibco_discoverer.createFileSystem(shell)

            bw = tibco_discoverer.BusinessWorksDiscoverer(
            ).findBWVersionFromPath(bwPath)
            domains = tibco_discoverer.BusinessWorksDomainDiscoverer(
                shell, fs).discover(bwPath)
            traHomeDiscoverer = tibco_discoverer.TicboTraHomeDiscoverer(shell)
            traHomes = traHomeDiscoverer.discover()
            fallbackDnsResolver = tibco_discoverer.FallbackResolver([
                netutils.JavaDnsResolver(),
                netutils.DnsResolverByShell(shell)
            ])
            dnsResolver = tibco_discoverer.CachedResolver(fallbackDnsResolver)

            if traHomes and bw:
                traPath = traHomes[0]
                for domain in domains:
                    logger.info("Visit %s" % domain)
                    try:
                        applications = None
                        # Check if we have any credential for TIBCO
                        if credList:
                            for credId in credList:
                                adminCommand = tibco_discoverer.AppManageAdminCommand(
                                    client, credId, "./")
                                adapterDiscoverer = tibco_discoverer.TibcoAdapterDiscoverer(
                                    dnsResolver)
                                appDiscoverer = tibco_discoverer.BusinessWorksApplicationDiscoverer(
                                    shell, fs, adminCommand, adapterDiscoverer)
                                applications = appDiscoverer.discover(
                                    domain.getName(),
                                    traPath,
                                    tmpDirPath,
                                    discoverJmsTopology=isDiscoverJms)
                            if applications:
                                tibco.each(domain.addApplication, applications)
                        else:
                            msg = errormessages.makeErrorMessage(
                                tibco.TIBCO_PROTOCOL,
                                pattern=errormessages.ERROR_NO_CREDENTIALS)
                            errobj = errorobject.createError(
                                errorcodes.NO_CREDENTIALS_FOR_TRIGGERED_IP,
                                [tibco.TIBCO_PROTOCOL], msg)
                            logger.reportErrorObject(errobj)

                        bw.addDomain(domain)
                    except tibco_discoverer.TibcoDiscovererException, exc:
                        logger.debugException(str(exc))
                        errorobj = errorobject.createError(
                            errorcodes.
                            FAILED_RUNNING_DISCOVERY_WITH_CLIENT_TYPE,
                            ['tibco', 'error: %s' % str(exc)], str(exc))
                        logger.reportErrorObject(errorobj)
        except:
            logger.debugException('')
            exInfo = logger.prepareJythonStackTrace(
                '[' + __name__ + ':DiscoveryMain] Error connecting: ')
            errormessages.resolveAndReport(exInfo, protocol, Framework)
        else:
            # Reporting
            logger.debug("--- Start reporting ---")
            reporter = tibco.TopologyReporter(tibco.TopologyBuilder())
            bwOsh = reporter.reportBusinessWorks(bw, hostOsh, bwId)
            OSHVResult.add(bwOsh)
            endpointReporter = netutils.EndpointReporter(
                netutils.ServiceEndpointBuilder())

            for domain in domains:
                domainOsh = reporter.reportBusinessWorksDomain(domain)
                OSHVResult.add(domainOsh)
                OSHVResult.add(reporter.reportBWAndDomainLink(
                    domainOsh, bwOsh))
                for app in domain.getApplications():
                    appOsh = reporter.reportBusinessWorksApp(app, bwOsh)
                    OSHVResult.add(appOsh)
                    if app.getJmsServers():
                        for jmsServer in app.getJmsServers():

                            # Trying to resolver host name
                            try:
                                ip = netutils.getLowestIp(
                                    dnsResolver.resolveIpsByHostname(
                                        jmsServer.hostname))
                                if ip:
                                    jmsServer.hostname = ip
                            except Exception, ex:
                                logger.debugException(str(ex))

                            if netutils.isValidIp(
                                    jmsServer.hostname
                            ) and not netutils.isLoopbackIp(
                                    jmsServer.hostname):
                                jmsHostOsh = modeling.createHostOSH(
                                    jmsServer.hostname)
                                emsServerOsh = reporter.reportEMSServer(
                                    tibco.EmsServer(), jmsHostOsh)
                                jmsServerOsh = reporter.reportJmsServer(
                                    jmsServer, emsServerOsh)
                                endpoint = netutils.createTcpEndpoint(
                                    jmsServer.hostname, jmsServer.getPort())
                                serviceOsh = endpointReporter.reportEndpoint(
                                    endpoint, jmsHostOsh)
                                linkOsh = reporter.reportEmsServerServiceAddressLink(
                                    emsServerOsh, serviceOsh)
                                OSHVResult.add(emsServerOsh)
                                OSHVResult.add(jmsHostOsh)
                                OSHVResult.add(jmsServerOsh)
                                OSHVResult.add(serviceOsh)
                                OSHVResult.add(linkOsh)
                                for jmsQueue in app.getJmsQueues():
                                    OSHVResult.addAll(
                                        reporter.reportJmsDestinationTopology(
                                            jmsQueue, jmsServerOsh, appOsh))
                                for jmsTopic in app.getJmsTopics():
                                    OSHVResult.addAll(
                                        reporter.reportJmsDestinationTopology(
                                            jmsTopic, jmsServerOsh, appOsh))
                    if app.getAdapters():
                        for adapter in app.getAdapters():
                            OSHVResult.addAll(
                                reporter.reportAdapterTopology(
                                    adapter, appOsh))

    finally:
        if shell:
            ## Close shell connection
            shell.closeClient()

    return OSHVResult
def DiscoveryMain(Framework):
    # import must be placed here as they are conflicts with import list in checkcred.py
    import jee
    import jmx
    import jee_connection
    import jee_discoverer
    import weblogic
    import weblogic_discoverer
    import protocol

    ports = jee_connection.getDestinationPorts(Framework)
    ip, domain = jee_connection.getIpAndDomain(Framework)
    ip = jee.IpDescriptor(ip)
    resultVector = ObjectStateHolderVector()
    protocolName = ClientsConsts.WEBLOGIC_PROTOCOL_NAME
    # FIND AVAILABLE PROTOCOLS
    protocols = jee_connection.getAvailableProtocols(Framework, protocolName,
                                                     ip.value())
    if not protocols:
        msg = errormessages.makeErrorMessage(
            protocolName, pattern=errormessages.ERROR_NO_CREDENTIALS)
        errobj = errorobject.createError(
            errorcodes.NO_CREDENTIALS_FOR_TRIGGERED_IP, [protocolName], msg)
        logger.reportErrorObject(errobj)
    else:
        # PREPARE CONNECTION MECHANISM
        platform = jee.Platform.WEBLOGIC
        spec = jee_connection.SpecificationByPorts(platform, ports)
        configManager = jee_connection.SucceededPortsConfigManager()
        factory = jee_connection.Factory(protocols, spec)

        connectionFailedMsgs = []
        discoveryFailedMsgs = []
        # ITERATOR OVER AVAILABLE CONNECTION CONFIGURATIONS AND MAKE ATTEMP TO ESTABLISH CONNECTION
        # TO THE PORT THAT HAVE NOT BEEN DISCOVERED PREVIOUSLY
        while factory.hasNextConnectionConfig():
            try:
                config = factory.next()
                if configManager.isSimilarConfigSucceeded(config):
                    continue
                client = factory.createClient(Framework, config)
            except (Exception, JException), exc:
                logger.warnException(
                    "Failed to establish connection using %s" % config)
                connectionFailedMsgs.append(str(exc))
            else:
                try:
                    try:
                        # CONNECTION ESTABLISHED - DISCOVER
                        dnsResolver = jee_discoverer.DnsResolverDecorator(
                            netutils.JavaDnsResolver(), client.getIpAddress())

                        credentialsfulServerRole = weblogic.HasCredentialInfoRole(
                            client.getUserName(),
                            client.getCredentialId(),
                            protocolType=protocol.getAttribute(
                                config.protocolObj,
                                AgentConstants.PROP_WEBLOGIC_PROTOCOL),
                            trustFileName=config.getProperty(
                                AgentConstants.PROP_WEBLOGIC_TRUST_FILE_NAME),
                            keyPemPath=config.getProperty(
                                AgentConstants.PROP_WEBLOGIC_KEY_PEM_PATH),
                            certPemPath=config.getProperty(
                                AgentConstants.PROP_WEBLOGIC_CERT_PEM_PATH))
                        # set port used for this connection
                        credentialsfulServerRole.connectionPort.set(
                            client.getPort())

                        # prepare builders and reporters
                        reporter = jee.ServerTopologyReporter(
                            weblogic.ServerTopologyBuilder())
                        # maker domain topology discovery
                        discoverer = weblogic_discoverer.ServerDiscovererByJmx(
                            jmx.Provider(client))
                        domain = discoverer.discoverRunningServersInDomain()
                        resultVector.addAll(
                            jee_discoverer.discoverDomainTopology(
                                config.portNumber.value(),
                                client.getIpAddress(), domain, dnsResolver,
                                credentialsfulServerRole, weblogic.ServerRole,
                                reporter))
                        configManager.processAsSuccessful(config)
                    except (Exception, JException), exc:
                        logger.warnException("Failed to make a discovery")
                        discoveryFailedMsgs.append(str(exc))
                finally:
                    if client is not None:
                        client.close()
        else:
Example #11
0
def DiscoveryMain(Framework):
    # import must be placed here as they are conflicts with import list in checkcred.py
    import jee
    import jmx
    import entity
    import jee_connection
    import jee_discoverer
    import websphere
    import websphere_discoverer

    ports = jee_connection.getDestinationPorts(Framework)
    ip = jee.IpDescriptor(Framework.getDestinationAttribute('ip_address'))
    platform = jee.Platform.WEBSPHERE
    # ESTABLISH CONNECTION
    # find all available protocols for the WebSphere
    protocolName = ClientsConsts.WEBSPHERE_PROTOCOL_NAME
    protocols = jee_connection.getAvailableProtocols(Framework, protocolName,
                                                     ip.value())
    resultVector = ObjectStateHolderVector()
    if not protocols:
        msg = errormessages.makeErrorMessage(
            protocolName, pattern=errormessages.ERROR_NO_CREDENTIALS)
        errobj = errorobject.createError(
            errorcodes.NO_CREDENTIALS_FOR_TRIGGERED_IP, [protocolName], msg)
        logger.reportErrorObject(errobj)
    else:
        # iterate over configurations defined for each protocol and try to establish connection
        dnsResolver = jee_discoverer.DnsResolverDecorator(
            netutils.JavaDnsResolver(), ip.value())

        spec = jee_connection.SpecificationByPorts(platform, ports)
        spec.addProperty(
            'server_was_config',
            'services:connectors:SOAP_CONNECTOR_ADDRESS:host,services:connectors:SOAP_CONNECTOR_ADDRESS:port,clusterName'
        )
        spec.addProperty('datasource_was_config',
                         'jndiName,URL,propertySet,connectionPool')
        factory = jee_connection.Factory(protocols, spec)
        connectionFailedMsgs = []
        discoveryFailedMsgs = []
        while factory.hasNextConnectionConfig():
            try:
                config = factory.next()
                client = factory.createClient(Framework, config)
                provider = jmx.Provider(client)
                hostOsh = modeling.createHostOSH(ip.value())
            except JException, je:
                logger.warnException(
                    "Failed to establish connection using %s" % config)
                connectionFailedMsgs.append(je.getMessage())
            else:
                # connection established
                try:
                    try:
                        credentialsfulServerRole = websphere.HasCredentialInfoRole(
                            client.getUserName(),
                            credentialsId=client.getCredentialId(),
                            keystoreFilePath=config.protocolObj.
                            getProtocolAttribute(
                                CollectorsConstants.
                                WEBSPHERE_PROTOCOL_ATTRIBUTE_KEYSTORE),
                            trustStoreFilePath=config.protocolObj.
                            getProtocolAttribute(
                                CollectorsConstants.
                                WEBSPHERE_PROTOCOL_ATTRIBUTE_TRUSTSTORE))
                        # create builder and reporter for server topology
                        reporter = jee.ServerTopologyReporter(
                            websphere.ServerTopologyBuilder())

                        # make discovery itself
                        discoverer = websphere_discoverer.ServerDiscovererByJmx(
                            jmx.Provider(client))
                        domain = discoverer.discoverServersInDomain()
                        resultVector.addAll(
                            jee_discoverer.discoverDomainTopology(
                                config.portNumber.value(),
                                client.getIpAddress(),
                                domain,
                                dnsResolver,
                                credentialsfulServerRole,
                                websphere.ServerRole,
                                reporter,
                                setDomainIp=0))
                        #trying to find config file serverindex to report ports
                        for node in domain.getNodes():
                            for server in node.getServers():
                                logger.debug(
                                    "trying to find config file serverindex for server: ",
                                    server)
                                filePath = 'cells\\' + domain.getName(
                                ) + '\\nodes\\' + server.nodeName + "\\" + 'serverindex.xml'
                                logger.debug('file path:', filePath)
                                try:
                                    fileContent = websphere_discoverer.getFileContent(
                                        provider, filePath)
                                    logger.debug('fileContent: ', fileContent)
                                    matches = re.findall(
                                        'port\s*=\s*\"(\d+)\"', fileContent)
                                    if matches:
                                        for match in matches:
                                            print("Found port:%s" % match)
                                            resultVector.addAll(
                                                reportServiceEndpoints(
                                                    ip.value(), match, hostOsh,
                                                    server))

                                except:
                                    logger.debug('Document not found: ',
                                                 filePath)

#                        sentObjectsCount += vector.size()
#                        _sendVectorImmediately(Framework, vector)
                    except (Exception, JException), exc:
                        logger.warnException("Failed to discover")
                        discoveryFailedMsgs.append(str(exc))
                finally:
                    if client is not None:
                        client.close()
        else: