Beispiel #1
0
def createDatabaseOSH(hostOSH, client, sid, version, appVersion):
    protType = client.getProtocolDbType()
    databaseType = ''
    applicationVersionNumber = None
    if protType == 'oracle':
        databaseType = 'oracle'
        applicationVersionNumber = resolveOracleVersion(version)
    elif protType == 'MicrosoftSQLServer':
        databaseType = 'sqlserver'
        applicationVersionNumber = resolveMSSQLVersion(version)
    elif protType == 'MicrosoftSQLServerNTLM':
        databaseType = 'sqlserver'
        applicationVersionNumber = resolveMSSQLVersion(version)
    else:
        errorMessage = 'Database type ' + str(protType) + 'not supported'
        raise Exception, errorMessage

    dbServerOSH = modeling.createDatabaseOSH(databaseType, sid,
                                             str(client.getPort()),
                                             client.getIpAddress(), hostOSH,
                                             client.getCredentialId(),
                                             client.getUserName(),
                                             client.getTimeout(), version,
                                             appVersion,
                                             applicationVersionNumber)
    return dbServerOSH
Beispiel #2
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:')
Beispiel #3
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:
Beispiel #4
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
 def reportTopology(self, vector, sid, endpoints, hostOsh):
     ip, port = endpoints[0]
     oracleOsh = modeling.createDatabaseOSH('oracle', sid, port, str(ip), hostOsh)
     vector.add(oracleOsh)
     for ip, port in endpoints:
         portOsh = modeling.createServiceAddressOsh(hostOsh, str(ip), port,
                                                    modeling.SERVICEADDRESS_TYPE_TCP)
         vector.add(portOsh)
         link = modeling.createLinkOSH('use', oracleOsh, portOsh)
         vector.add(link)
Beispiel #6
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    ip = Framework.getDestinationAttribute('ip_address')
    sid = Framework.getDestinationAttribute('sid')
    port = Framework.getDestinationAttribute('port')

    hostId = Framework.getDestinationAttribute('hostId')

    if (ip == None) or (ip == 'NA'):
        #checked and pass all IPs of given host
        ips = Framework.getTriggerCIDataAsList('host_ips')
    else:
        ips = [ip]
    for currIP in ips:
        if len(currIP) == 0:
            continue
        logger.debug('Checking sqlserver with no user on ipaddress:', currIP)
        protocols = Framework.getAvailableProtocols(
            currIP, ClientsConsts.SQL_PROTOCOL_NAME)
        for protocol in protocols:
            dbClient = None
            try:
                try:
                    if dbutils.protocolMatch(
                            Framework, protocol, 'microsoftsqlserver', sid,
                            port) or dbutils.protocolMatch(
                                Framework, protocol, 'microsoftsqlserverntlm',
                                sid, port):
                        props = Properties()
                        props.setProperty('ip_address', currIP)
                        dbClient = Framework.createClient(protocol, props)

                        hostOSH = modeling.createOshByCmdbIdString(
                            'host', hostId)
                        oracleOSH = modeling.createDatabaseOSH(
                            'sqlserver', sid, str(dbClient.getPort()),
                            dbClient.getIpAddress(), hostOSH, protocol, None,
                            dbClient.getTimeout(), dbClient.getDbVersion(),
                            dbClient.getAppVersion())
                        logger.debug(
                            'Successfully connected to sqlserver object ', sid,
                            ' on ', currIP)
                        OSHVResult.add(oracleOSH)
                        #since this is knownn oracle and we found credentials for it we can finish execution
                        return OSHVResult
                except:
                    if logger.isDebugEnabled():
                        logger.debugException(
                            'Unexpected CreateClient() for sqlserver client Exception:'
                        )
            finally:
                if dbClient != None:
                    dbClient.close()
    Framework.reportWarning('Failed to connect using all protocols')
    return OSHVResult
Beispiel #7
0
 def build(self, parentOsh):
     '''Builds the Oracle Database OSH
     @param parentOsh: root cointainer for the Oracle Database CI
     @return: Oracle Database OSH or None, if one of the prerequisits weren't met.
     '''
     if self.name:
         dbOsh = modeling.createDatabaseOSH('oracle', self.name, None, None, parentOsh)
         self.setApplicationIp(dbOsh)
         return dbOsh
     else:
         logger.error('Failed to create Oracle Database OSH. Database SID is not specified.')
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    ip = Framework.getDestinationAttribute("ip_address")
    sid = Framework.getDestinationAttribute("sid")
    port = Framework.getDestinationAttribute("port")

    hostId = Framework.getDestinationAttribute("hostId")

    if (ip == None) or (ip == "NA"):
        # checked and pass all IPs of given host
        ips = Framework.getTriggerCIDataAsList("host_ips")
    else:
        ips = [ip]
    for currIP in ips:
        if len(currIP) == 0:
            continue
        logger.debug("Checking sqlserver with no user on ipaddress:", currIP)
        protocols = Framework.getAvailableProtocols(currIP, ClientsConsts.SQL_PROTOCOL_NAME)
        for protocol in protocols:
            dbClient = None
            try:
                try:
                    if dbutils.protocolMatch(
                        Framework, protocol, "microsoftsqlserver", sid, port
                    ) or dbutils.protocolMatch(Framework, protocol, "microsoftsqlserverntlm", sid, port):
                        props = Properties()
                        props.setProperty("ip_address", currIP)
                        dbClient = Framework.createClient(protocol, props)

                        hostOSH = modeling.createOshByCmdbIdString("host", hostId)
                        oracleOSH = modeling.createDatabaseOSH(
                            "sqlserver",
                            sid,
                            str(dbClient.getPort()),
                            dbClient.getIpAddress(),
                            hostOSH,
                            protocol,
                            None,
                            dbClient.getTimeout(),
                            dbClient.getDbVersion(),
                            dbClient.getAppVersion(),
                        )
                        logger.debug("Successfully connected to sqlserver object ", sid, " on ", currIP)
                        OSHVResult.add(oracleOSH)
                        # since this is knownn oracle and we found credentials for it we can finish execution
                        return OSHVResult
                except:
                    if logger.isDebugEnabled():
                        logger.debugException("Unexpected CreateClient() for sqlserver client Exception:")
            finally:
                if dbClient != None:
                    dbClient.close()
    Framework.reportWarning("Failed to connect using all protocols")
    return OSHVResult
 def reportTopology(self, vector, sid, endpoints, hostOsh):
     ip, port = endpoints[0]
     oracleOsh = modeling.createDatabaseOSH('oracle', sid, port, str(ip),
                                            hostOsh)
     vector.add(oracleOsh)
     for ip, port in endpoints:
         portOsh = modeling.createServiceAddressOsh(
             hostOsh, str(ip), port, modeling.SERVICEADDRESS_TYPE_TCP)
         vector.add(portOsh)
         link = modeling.createLinkOSH('use', oracleOsh, portOsh)
         vector.add(link)
Beispiel #10
0
 def _buildDatabases(self):
     """
     Builds sqlserver CI from stored DbConnection elements
     ->None
     """
     logger.debug('_buildDatabases')
     for dbConnection in self._databaseConnections:
         farmMember = self._getFarmMember(dbConnection.hostName)
         dbOsh = self._dbNameToDbOsh.get(dbConnection.name)
         if not dbOsh:
             logger.debug('building DB %s' % dbConnection.name)
             dbOsh = modeling.createDatabaseOSH('sqlserver', dbConnection.name, 0, farmMember.ip, farmMember.hostOsh)
             self._dbNameToDbOsh[dbConnection.name] = dbOsh
Beispiel #11
0
 def build(self, parentOsh):
     '''Builds the Oracle Database OSH
     @param parentOsh: root cointainer for the Oracle Database CI
     @return: Oracle Database OSH or None, if one of the prerequisits weren't met.
     '''
     if self.name:
         dbOsh = modeling.createDatabaseOSH('oracle', self.name, None, None,
                                            parentOsh)
         self.setApplicationIp(dbOsh)
         return dbOsh
     else:
         logger.error(
             'Failed to create Oracle Database OSH. Database SID is not specified.'
         )
Beispiel #12
0
 def buildSybaseServer(self, sybaseServer):
     if not sybaseServer:
         raise ValueError('Sybase Server is not specified')
     serverName = sybaseServer.getName()
     client = sybaseServer.getClient()
     host = sybaseServer.getHost()
     hostOSH = modeling.createHostOSH(host)
     protocol = sybaseServer.getProtocol()
     osh = modeling.createDatabaseOSH('sybase', serverName,
                                      str(client.getPort()),
                                      client.getIpAddress(),
                                      hostOSH, protocol,
                                      client.getUserName(), None,
                                      client.getDbVersion())
     return osh
Beispiel #13
0
 def createOracleTopology(self, parsedData, applicationOsh):
     vector = ObjectStateHolderVector()
     if not parsedData["serverIp"] and parsedData["sid"]:
         return vector
     hostOsh = modeling.createHostOSH(parsedData["serverIp"])
     dbOsh = modeling.createDatabaseOSH('oracle', parsedData["sid"], parsedData["port"], parsedData["serverIp"], hostOsh)
     serviceEndPointOsh = modeling.createServiceAddressOsh(hostOsh, parsedData["serverIp"], parsedData["port"], 1)
     clientServerLinkOsh = modeling.createLinkOSH('client_server', applicationOsh, serviceEndPointOsh)
     clientServerLinkOsh.setStringAttribute('clientserver_protocol', 'tcp')
     usageLinkOsh = modeling.createLinkOSH('usage', dbOsh, serviceEndPointOsh)
     vector.add(hostOsh)
     vector.add(dbOsh)
     vector.add(serviceEndPointOsh)
     vector.add(clientServerLinkOsh)
     vector.add(usageLinkOsh)
     return vector
Beispiel #14
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:
Beispiel #15
0
def createDatabaseOSH(hostOSH,
                      client,
                      sid,
                      dbVersion,
                      appVersion,
                      buildNumber=None,
                      edition=None):
    protType = client.getProtocolDbType().lower()
    (versionResolver, databaseType) = dbMetaParams[protType]
    applicationVersionNumber = versionResolver(dbVersion)
    return modeling.createDatabaseOSH(databaseType, sid, str(client.getPort()),
                                      client.getIpAddress(), hostOSH,
                                      client.getCredentialId(),
                                      client.getUserName(),
                                      client.getTimeout(), dbVersion,
                                      appVersion, applicationVersionNumber,
                                      buildNumber, edition)
Beispiel #16
0
def createDatabaseOSH(hostOSH, client, sid, dbVersion, appVersion, buildNumber=None, edition=None):
    protType = client.getProtocolDbType().lower()
    (versionResolver, databaseType) = dbMetaParams[protType]
    applicationVersionNumber = versionResolver(dbVersion)
    return modeling.createDatabaseOSH(databaseType,
                                             sid,
                                             str(client.getPort()),
                                             client.getIpAddress(),
                                             hostOSH,
                                             client.getCredentialId(),
                                             client.getUserName(),
                                             client.getTimeout(),
                                             dbVersion,
                                             appVersion,
                                             applicationVersionNumber,
                                             buildNumber,
                                             edition)
def DiscoveryMain(Framework):
	OSHVResult = ObjectStateHolderVector()
	ip = Framework.getDestinationAttribute('ip_address')
	sid = Framework.getDestinationAttribute('sid')
	port = Framework.getDestinationAttribute('port')
	
	hostId	  = Framework.getDestinationAttribute('hostId')
	

	if (ip == None) or (ip == 'NA'):
		#checked and pass all IPs of given host
		ips = Framework.getTriggerCIDataAsList('host_ips')
	else:
		ips = [ip]
	for currIP in ips:
		if len(currIP) == 0:
			continue
		logger.debug('Checking oracle with no user on ipaddress:', currIP)
		protocols = Framework.getAvailableProtocols(currIP, ClientsConsts.SQL_PROTOCOL_NAME)
		for protocol in protocols:
			dbClient = None
			try:
				try:
					if dbutils.protocolMatch(Framework, protocol, 'oracle', sid, port):
						props = Properties()
						props.setProperty('ip_address', currIP)
						dbClient = Framework.createClient(protocol, props)

						hostOSH = modeling.createOshByCmdbIdString('host', hostId)
						oracleOSH = modeling.createDatabaseOSH('oracle', sid, str(dbClient.getPort()), dbClient.getIpAddress(), hostOSH, protocol,None, dbClient.getTimeout(),dbClient.getDbVersion(), dbClient.getAppVersion())
						logger.debug('Successfully connected to oracle object ', sid, ' on ', currIP)
						OSHVResult.add(oracleOSH)
						#since this is knownn oracle and we found credentials for it we can finish execution
						return OSHVResult
				except:			
					if logger.isDebugEnabled():
						logger.debugException('Unexpected CreateClient() for oracle client Exception:')
			finally:
				if dbClient != None:
					dbClient.close()
	Framework.reportWarning('Failed to connect using all protocols')
	return OSHVResult
 def reportTopology(self, context, dbType, port, sid, dbHostIp):
     if re.search('oracle', dbType, re.I):
         dbType = 'oracle'
     elif re.search('sql', dbType, re.I):
         dbType = 'sqlserver'
     else:
         logger.error('Unsupported DB type for uCMDB configuration')
     hostOSH = modeling.createHostOSH(dbHostIp)
     ipOSH = modeling.createIpOSH(dbHostIp)
     link = modeling.createLinkOSH('contained', hostOSH, ipOSH)
     dbOSH = modeling.createDatabaseOSH(dbType, sid, port, dbHostIp, hostOSH)
     serviceAddress = modeling.createServiceAddressOsh(hostOSH, dbHostIp,
                                     port, modeling.SERVICEADDRESS_TYPE_TCP)
     context.resultsVector.add(hostOSH)
     context.resultsVector.add(ipOSH)
     context.resultsVector.add(dbOSH)
     context.resultsVector.add(link)
     link = modeling.createLinkOSH('use', dbOSH, serviceAddress)
     context.resultsVector.add(serviceAddress)
     context.resultsVector.add(link)
def createDatabaseOSH(hostOSH, client, sid, version, appVersion):
    protType = client.getProtocolDbType()
    databaseType = ''
    applicationVersionNumber = None
    if protType == 'oracle':
        databaseType = 'oracle'
        applicationVersionNumber = resolveOracleVersion(version)
    elif protType == 'MicrosoftSQLServer':
        databaseType = 'sqlserver'
        applicationVersionNumber = resolveMSSQLVersion(version)
    elif protType == 'MicrosoftSQLServerNTLM':
        databaseType = 'sqlserver'
        applicationVersionNumber = resolveMSSQLVersion(version)
    else:
        errorMessage = 'Database type ' + str(protType) + 'not supported'
        raise Exception, errorMessage
    
        
    dbServerOSH = modeling.createDatabaseOSH(databaseType, sid, str(client.getPort()), client.getIpAddress(), hostOSH,client.getCredentialId(),client.getUserName(),client.getTimeout(),version, appVersion, applicationVersionNumber)
    return dbServerOSH
 def reportTopology(self, context, dbType, port, sid, dbHostIp):
     if re.search('oracle', dbType, re.I):
         dbType = 'oracle'
     elif re.search('sql', dbType, re.I):
         dbType = 'sqlserver'
     else:
         logger.error('Unsupported DB type for uCMDB configuration')
     hostOSH = modeling.createHostOSH(dbHostIp)
     ipOSH = modeling.createIpOSH(dbHostIp)
     link = modeling.createLinkOSH('contained', hostOSH, ipOSH)
     dbOSH = modeling.createDatabaseOSH(dbType, sid, port, dbHostIp,
                                        hostOSH)
     serviceAddress = modeling.createServiceAddressOsh(
         hostOSH, dbHostIp, port, modeling.SERVICEADDRESS_TYPE_TCP)
     context.resultsVector.add(hostOSH)
     context.resultsVector.add(ipOSH)
     context.resultsVector.add(dbOSH)
     context.resultsVector.add(link)
     link = modeling.createLinkOSH('use', dbOSH, serviceAddress)
     context.resultsVector.add(serviceAddress)
     context.resultsVector.add(link)
Beispiel #21
0
 def createOracleTopology(self, parsedData, applicationOsh):
     vector = ObjectStateHolderVector()
     if not parsedData["serverIp"] and parsedData["sid"]:
         return vector
     hostOsh = modeling.createHostOSH(parsedData["serverIp"])
     dbOsh = modeling.createDatabaseOSH('oracle', parsedData["sid"],
                                        parsedData["port"],
                                        parsedData["serverIp"], hostOsh)
     serviceEndPointOsh = modeling.createServiceAddressOsh(
         hostOsh, parsedData["serverIp"], parsedData["port"], 1)
     clientServerLinkOsh = modeling.createLinkOSH('client_server',
                                                  applicationOsh,
                                                  serviceEndPointOsh)
     clientServerLinkOsh.setStringAttribute('clientserver_protocol', 'tcp')
     usageLinkOsh = modeling.createLinkOSH('usage', dbOsh,
                                           serviceEndPointOsh)
     vector.add(hostOsh)
     vector.add(dbOsh)
     vector.add(serviceEndPointOsh)
     vector.add(clientServerLinkOsh)
     vector.add(usageLinkOsh)
     return vector
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:")
def handleResource(element_name, element_type, element_prop, vcsresourceOSH,
                   nodeNameToOSH, OSHVResult, clusterDeviceOSH):
    #this routine handles resources of type IP or Oracle and creates the proper objects and links for those resources

    if element_type == 'Oracle':
        # Create the oracle database instance on all relevant nodes

        sid = None
        oracleIP = None
        oraclePort = None

        try:
            sidRes = re.search('Sid\s*?(?:[@\w]*?)*?\s*?=\s*?(\w+)',
                               element_prop)
            if (sidRes):
                sid = sidRes.group(1).strip()
            oipRes = re.search('IPAddr\s*?=\s*?[\'"]?([.\d]+)[\'"]?',
                               element_prop)
            oportRes = re.search('Portnum\s*?=\s*?[\'"]?([\d]+)[\'"]?',
                                 element_prop)
            if oipRes:
                oracleIP = oipRes.group(1).strip()
            if oportRes:
                oraclePort = oportRes.group(1).strip()
        except:
            return

        oracleApplicationOsh = modeling.createDatabaseOSH(
            element_type.lower(), sid, oraclePort, oracleIP, clusterDeviceOSH)
        OSHVResult.add(oracleApplicationOsh)
        if oracleIP and oraclePort:
            oracleSAOSH = modeling.createServiceAddressOsh(
                clusterDeviceOSH, oracleIP, oraclePort,
                modeling.SERVICEADDRESS_TYPE_TCP, 'oracle')
            useLinkOSH = modeling.createLinkOSH('use', oracleApplicationOsh,
                                                oracleSAOSH)
            OSHVResult.add(oracleSAOSH)
            OSHVResult.add(useLinkOSH)

    if element_type in ['SQLServer2000', 'SQLServer2005', 'SQLServer2008']:
        # Create the oracle database instance on all relevant nodes

        instanceName = None
        instanceIP = None
        instancePort = None
        instanceUser = None
        instanceDomain = None
        CRG = None

        try:
            inRes = re.search('Instance\s*?=\s*?([.\-_\w]+)', element_prop)
            if (inRes):
                instanceName = inRes.group(1).strip()
            domainRes = re.search('Domain\s*?=\s*?([.\-_\w]+)', element_prop)
            if domainRes:
                instanceDomain = domainRes.group(1).strip()
            userRes = re.search('Username\s*?=\s*?([.\-_\w]+)', element_prop)
            if userRes:
                instanceUser = userRes.group(1).strip()
            CRG = clusterDeviceOSH.getAttribute('data_name').getValue()
            sipRes = re.search('IPAddr\s*?=\s*?[\'"]?([.\d]+)[\'"]?',
                               element_prop)
            sportRes = re.search('Portnum\s*?=\s*?[\'"]?([\d]+)[\'"]?',
                                 element_prop)
            if sipRes:
                instanceIP = sipRes.group(1).strip()
            if sportRes:
                instancePort = sportRes.group(1).strip()
        except:
            return

        if CRG and instanceName:
            instanceName = CRG + '\\' + instanceName

        if instanceDomain:
            instanceUser = instanceDomain + '\\' + instanceUser

        sqlApplicationOsh = modeling.createDatabaseOSH(
            'sqlserver', instanceName, instancePort, instanceIP,
            clusterDeviceOSH, None, instanceUser)
        OSHVResult.add(sqlApplicationOsh)
        if instanceIP and instancePort:
            sqlSAOSH = modeling.createServiceAddressOsh(
                clusterDeviceOSH, instanceIP, instancePort,
                modeling.SERVICEADDRESS_TYPE_TCP, 'sql')
            useLink = modeling.createLinkOSH('use', sqlApplicationOsh,
                                             sqlSAOSH)
            OSHVResult.add(sqlSAOSH)
            OSHVResult.add(useLink)

    if element_type == 'MySQL':
        # Create the oracle database instance on all relevant nodes

        sid = None
        mysqlPort = None
        mysqlIP = None

        try:
            ipRes = re.search('IPAddr\s*?=\s*?[\'"]?([.\d]+)[\'"]?',
                              element_prop)
            portRes = re.search('Portnum\s*?=\s*?[\'"]?([\d]+)[\'"]?',
                                element_prop)
            if ipRes:
                mysqlIP = ipRes.group(1).strip()
            if portRes:
                mysqlPort = portRes.group(1).strip()
            if mysqlPort:
                sid = 'MySQL on port ' + mysqlPort
        except:
            return
        if mysqlIP and mysqlPort:
            serviceAddrOSH = modeling.createServiceAddressOsh(
                clusterDeviceOSH, mysqlIP, mysqlPort,
                modeling.SERVICEADDRESS_TYPE_TCP, 'mysql')
            applicationOsh = modeling.createDatabaseOSH(
                element_type.lower(), sid, mysqlPort, mysqlIP,
                clusterDeviceOSH)
            useLinkOSH = modeling.createLinkOSH('use', applicationOsh,
                                                serviceAddrOSH)
            OSHVResult.add(serviceAddrOSH)
            OSHVResult.add(useLinkOSH)
            OSHVResult.add(applicationOsh)

    if element_type in ['IP', 'IPMultiNIC', 'IPMultiNICB']:

        # Create the IP instance and connect it to the resource
        addr = None
        mask = None

        try:
            addrRes = re.search('Address\s*?=\s*?[\'"](.*)[\'"]', element_prop)
            if (addrRes):
                addr = addrRes.group(1).strip()
            else:
                logger.warn('NO ADDR')
            maskRes = re.search('NetMask\s*?=\s*?[\'"](.*)[\'"]', element_prop)
            if (maskRes):
                mask = maskRes.group(1).strip()
            else:
                logger.warn('NO MASK')
        except:
            logger.error('ERROR handling resource')
            addr = None
            mask = None

        if (addr != None) and (mask != None):

            ipOSH = modeling.createIpOSH(addr)
            ipOSH.setAttribute('ip_netmask', mask)
            OSHVResult.add(ipOSH)

            # Add depend link between the database and the resource element
            containedOSH = modeling.createLinkOSH('contained',
                                                  clusterDeviceOSH, ipOSH)
            OSHVResult.add(containedOSH)
def handleResource(element_name, element_type, element_prop, vcsresourceOSH, nodeNameToOSH, OSHVResult, clusterDeviceOSH):
    #this routine handles resources of type IP or Oracle and creates the proper objects and links for those resources
    
    if element_type == 'Oracle':
        # Create the oracle database instance on all relevant nodes
        
        sid = None
        oracleIP = None
        oraclePort = None

        try:
            sidRes = re.search('Sid\s*?(?:[@\w]*?)*?\s*?=\s*?(\w+)',element_prop)
            if(sidRes):
                sid = sidRes.group(1).strip()
            oipRes = re.search('IPAddr\s*?=\s*?[\'"]?([.\d]+)[\'"]?',element_prop)
            oportRes = re.search('Portnum\s*?=\s*?[\'"]?([\d]+)[\'"]?',element_prop)
            if oipRes:
                oracleIP = oipRes.group(1).strip()
            if oportRes:
                oraclePort = oportRes.group(1).strip()
        except:
            return
        
        oracleApplicationOsh = modeling.createDatabaseOSH(element_type.lower(), sid, oraclePort, oracleIP, clusterDeviceOSH) 
        OSHVResult.add(oracleApplicationOsh)
        if oracleIP and oraclePort:
            oracleSAOSH = modeling.createServiceAddressOsh(clusterDeviceOSH,oracleIP,oraclePort,modeling.SERVICEADDRESS_TYPE_TCP,'oracle')
            useLinkOSH = modeling.createLinkOSH('use',oracleApplicationOsh,oracleSAOSH)
            OSHVResult.add(oracleSAOSH)
            OSHVResult.add(useLinkOSH)

    if element_type in ['SQLServer2000','SQLServer2005','SQLServer2008']:
        # Create the oracle database instance on all relevant nodes
        
        instanceName = None
        instanceIP = None
        instancePort = None
        instanceUser = None
        instanceDomain = None
        CRG = None

        try:
            inRes = re.search('Instance\s*?=\s*?([.\-_\w]+)',element_prop)
            if(inRes):
                instanceName = inRes.group(1).strip()
            domainRes = re.search('Domain\s*?=\s*?([.\-_\w]+)',element_prop)
            if domainRes:
                instanceDomain = domainRes.group(1).strip()
            userRes = re.search('Username\s*?=\s*?([.\-_\w]+)',element_prop)
            if userRes:
                instanceUser = userRes.group(1).strip()            
            CRG = clusterDeviceOSH.getAttribute('data_name').getValue()
            sipRes = re.search('IPAddr\s*?=\s*?[\'"]?([.\d]+)[\'"]?',element_prop)
            sportRes = re.search('Portnum\s*?=\s*?[\'"]?([\d]+)[\'"]?',element_prop)
            if sipRes:
                instanceIP = sipRes.group(1).strip()
            if sportRes:
                instancePort = sportRes.group(1).strip()
        except:
            return
        
        if CRG and instanceName:
            instanceName = CRG + '\\' + instanceName
        
        if instanceDomain:
            instanceUser = instanceDomain + '\\' + instanceUser
        
        sqlApplicationOsh = modeling.createDatabaseOSH('sqlserver', instanceName, instancePort, instanceIP, clusterDeviceOSH, None, instanceUser) 
        OSHVResult.add(sqlApplicationOsh)
        if instanceIP and instancePort:
            sqlSAOSH = modeling.createServiceAddressOsh(clusterDeviceOSH,instanceIP,instancePort,modeling.SERVICEADDRESS_TYPE_TCP,'sql')
            useLink = modeling.createLinkOSH('use',sqlApplicationOsh,sqlSAOSH)
            OSHVResult.add(sqlSAOSH)
            OSHVResult.add(useLink)

    if element_type == 'MySQL':
        # Create the oracle database instance on all relevant nodes
        
        sid = None
        mysqlPort = None
        mysqlIP = None

        try:
            ipRes = re.search('IPAddr\s*?=\s*?[\'"]?([.\d]+)[\'"]?',element_prop)
            portRes = re.search('Portnum\s*?=\s*?[\'"]?([\d]+)[\'"]?',element_prop)
            if ipRes:
                mysqlIP = ipRes.group(1).strip()
            if portRes:
                mysqlPort = portRes.group(1).strip()
            if mysqlPort:
                sid = 'MySQL on port ' + mysqlPort
        except:
            return
        if mysqlIP and mysqlPort:
            serviceAddrOSH = modeling.createServiceAddressOsh(clusterDeviceOSH, mysqlIP, mysqlPort, modeling.SERVICEADDRESS_TYPE_TCP, 'mysql')            
            applicationOsh = modeling.createDatabaseOSH(element_type.lower(), sid, mysqlPort, mysqlIP, clusterDeviceOSH)
            useLinkOSH = modeling.createLinkOSH('use',applicationOsh,serviceAddrOSH)
            OSHVResult.add(serviceAddrOSH)
            OSHVResult.add(useLinkOSH)
            OSHVResult.add(applicationOsh)

    if element_type in ['IP', 'IPMultiNIC','IPMultiNICB']:

        # Create the IP instance and connect it to the resource
        addr = None
        mask = None

        try:
            addrRes = re.search('Address\s*?=\s*?[\'"](.*)[\'"]',element_prop)
            if(addrRes):
                addr = addrRes.group(1).strip()
            else:
                logger.warn('NO ADDR')
            maskRes = re.search('NetMask\s*?=\s*?[\'"](.*)[\'"]',element_prop)
            if(maskRes):
                mask = maskRes.group(1).strip()
            else:
                logger.warn('NO MASK')
        except:
            logger.error('ERROR handling resource')
            addr = None
            mask = None

        if (addr != None) and (mask != None):

            ipOSH = modeling.createIpOSH(addr)
            ipOSH.setAttribute('ip_netmask', mask)
            OSHVResult.add(ipOSH)

            # Add depend link between the database and the resource element
            containedOSH = modeling.createLinkOSH('contained', clusterDeviceOSH, ipOSH)
            OSHVResult.add(containedOSH)
Beispiel #25
0
def infrastructure(client, OSHVResult, Framework, schemaName = None, viewSchemaName = None):
    retOSHs = ArrayList(4)
    retOSHs.add(None)
    retOSHs.add(None)
    retOSHs.add(None)
    retOSHs.add(None)

    systemOSH = ObjectStateHolder('oraclesystem')
    systemOSH.setAttribute('data_name', client.getSid())
    systemOSH.setAttribute('oraclesystem_dbaddress', client.getIpAddress())
    modeling.setAppSystemVendor(systemOSH)
    
    webServerOSH = None
    nameToHostOSH = HashMap()
    hostToServerOSH = HashMap()
    hostToIpAddress = HashMap()
    databasesOSH = HashMap()

    resultSet = None
    try:
        objs = __assocWithSchemaName(['FND_OAM_APP_SYS_STATUS'], schemaName, viewSchemaName) 
        # query a special table that holds Applications System Status related information
        resultSet = client.executeQuery('SELECT * FROM %s' % objs)#@@CMD_PERMISION sql protocol execution
    except:
        logger.debugException('SQL query failure. "SELECT * FROM FND_OAM_APP_SYS_STATUS"')
        Framework.reportWarning('No Oracle E-Business Suite components found.')

    if resultSet:
        OSHVResult.add(systemOSH)
        retOSHs.set(0, systemOSH)
    else:
        return None
        
    while resultSet.next():
        name = resultSet.getString(1)
        dbSid = resultSet.getString(4)
        status = resultSet.getString(6)
        host = resultSet.getString(7)
        port = client.getPort()
        
        if logger.isDebugEnabled():
            logger.debug('-----------------------------')
            logger.debug('name = ', name)
            logger.debug('status = ', status)
            if host != None:
                logger.debug('host = ', host)
            else:
                logger.debug('skipping Application system with None host')
                continue
            logger.debug('-----------------------------')
        hostOSH = nameToHostOSH.get(host)
        serverOSH = hostToServerOSH.get(host)
        hostIP = hostToIpAddress.get(host)

        if not hostIP:
            hostIP = netutils.getHostAddress(host, host)

        if hostOSH == None and netutils.isValidIp(hostIP):
            hostOSH = modeling.createHostOSH(hostIP)
            OSHVResult.add(hostOSH)
            nameToHostOSH.put(host,hostOSH)
            hostToIpAddress.put(host,hostIP)

        if hostOSH == None:
            logger.warn('Failed to created host [', host, ']')
            continue

        if serverOSH == None:
            serverOSH = modeling.createJ2EEServer('oracleias', hostIP, None, hostOSH, host)
            OSHVResult.add(serverOSH)
            hostToServerOSH.put(host,serverOSH)
            serverMemberOSH = modeling.createLinkOSH('member', systemOSH, serverOSH)
            OSHVResult.add(serverMemberOSH)
        if name.find('WEB_SERVER') == 0 and host != None:
            webServerOSH = serverOSH
            serverOSH.setBoolAttribute('oracleias_web', 1)
        elif name.find('FORMS_SERVER') == 0 and host != None:
            serverOSH.setBoolAttribute('oracleias_form', 1)
        elif name.find('ADMIN_SERVER') == 0 and host != None:
            serverOSH.setBoolAttribute('oracleias_admin', 1)
        elif name.find('CP_SERVER') == 0 and host != None:            
            serverOSH.setBoolAttribute('oracleias_concurrentprocessing', 1)
        elif name.find('DATABASE') == 0 and host != None:
            dbOSH = modeling.createDatabaseOSH('oracle', dbSid, port, hostIP, hostOSH)
            OSHVResult.add(dbOSH)
            databasesOSH.put(dbSid,dbOSH)
            memberOSH = modeling.createLinkOSH('member', systemOSH, dbOSH)
            OSHVResult.add(memberOSH)
    resultSet.close()
    try:
        systemMetrics(client,systemOSH,webServerOSH, OSHVResult, schemaName, viewSchemaName)
    except:
        logger.debug("Failed to get system metrics")
    retOSHs.set(1, hostToServerOSH)
    retOSHs.set(2, nameToHostOSH)
    retOSHs.set(3, databasesOSH)
    return retOSHs    
Beispiel #26
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    shell = None
    protocol = Framework.getDestinationAttribute('Protocol')
    listenerName = Framework.getDestinationAttribute('listenerName')
    listenerPath = Framework.getDestinationAttribute('listener_process_path')
    defOraHomes = Framework.getParameter('OracleHomes')
    listenerIp = Framework.getDestinationAttribute('listener_ip')
    listenedIPs = Framework.getTriggerCIDataAsList('listened_ips')

    try:
        try:
            client = Framework.createClient()
            shell = shellutils.ShellUtils(client)

            if listenerPath:
                envConf = UnixOracleEnvConfig(shell)
                if shell.isWinOs():
                    envConf = WindowsOracleEnvConfig(shell)
                envConf.setOracleHomeEnvVar(listenerPath)
            else:
                envConf = EnvConfigurator(shell, defOraHomes)

            if not listenedIPs:
                Framework.reportError(
                    'No listened_ips attribute values found.')
                return OSHVResult
            lookuper = LookupManager(listenedIPs)

            serviceToNodesMap = {}
            srvDiscoverer = SrvctlBasedDiscoverer(shell, envConf)
            databases = srvDiscoverer.getDatabases()
            for database in databases:
                instanceAndNodes = srvDiscoverer.getInstancesWithNodes(
                    database)
                if instanceAndNodes:
                    serviceToNodesMap[database] = instanceAndNodes
                    for elem in instanceAndNodes:
                        resolver = DNSResolver(shell, elem.get('Node'))
                        ipAddr = resolver.resolveNSLookup()
                        if not ipAddr:
                            ipAddr = resolver.resolveNSLookupAliasBased()
                            ipAddr = ipAddr and ipAddr[0]
                            try:
                                if not ipAddr:
                                    ipAddr = resolver.resolveHostsFile()
                            except:
                                pass
                        elem['ip'] = ipAddr

            for (serviceName, params) in serviceToNodesMap.items():
                try:
                    listeners = []
                    oracles = []
                    for elem in params:
                        ipAddr = elem.get('ip')
                        if not ipAddr:
                            raise ValueError(
                                'One of the Node Ip is not discovered. Can not create full topology.'
                            )
                        hostOSH = modeling.createHostOSH(ipAddr)
                        OSHVResult.add(hostOSH)
                        listenerOSH = createWeakListener(hostOSH)
                        if listenerIp == ipAddr:
                            listenerOSH.setStringAttribute(
                                'name', listenerName)
                        listeners.append(listenerOSH)
                        oracleOsh = modeling.createDatabaseOSH(
                            'oracle', elem['Instance'], None, ipAddr, hostOSH)
                        listeners.append(oracleOsh)
                        oracles.append(oracleOsh)
                    racName = ''
                    nodes = [x['Node'] for x in params if x['Node']]
                    nodes.sort()
                    racName = ':'.join(nodes)
                    racOsh = createRacOSH(racName, len(params), serviceName,
                                          None)
                    OSHVResult.add(racOsh)
                    for listener in listeners:
                        OSHVResult.add(listener)
                        OSHVResult.add(
                            modeling.createLinkOSH('member', racOsh, listener))
                    for oracle in oracles:
                        OSHVResult.add(oracle)
                        OSHVResult.add(
                            modeling.createLinkOSH('member', racOsh, oracle))
                except:
                    Framework.reportWarning(
                        'Failed to lookup host name of the node. Probably not all nodes were discovered by \"Oracle Listener by Shell\" Job. No RAC CI will be created.'
                    )
                    logger.warn(
                        'Failed to lookup host name for node with ip. No RAC CI will be created.'
                    )
            if not serviceToNodesMap:
                logger.warn(
                    'Failed to get information via srvctl. Will use old approach.'
                )
            else:
                return OSHVResult
            #old flow
            tnsConfig = {}
            try:
                tnsConfig = TNSNamesConfig(shell, envConf)
            except:
                logger.debug(
                    'Failed to get tnsnames.ora. Trying different home.')
                envConf = EnvConfigurator(shell, defOraHomes)
                oraHome = envConf.findMatchingDefaultOracleHome()
                envConf = UnixOracleEnvConfig(shell)
                envConf.setOracleHomeEnvVar(oraHome)
                tnsConfig = TNSNamesConfig(shell, envConf)

            racParams = tnsConfig.getRacParams()
            servChec = ServiceChecker(shell,
                                      envConf,
                                      listenerName=listenerName)
            for racServiceName in racParams.keys():
                parametersDict = racParams[racServiceName]
                racNodeNameList = []
                racInstCount = len(parametersDict.keys())

                if not servChec.isServiceRunning(racServiceName.upper(
                )) or racInstCount == 0 or racInstCount != int(
                        servChec.getServiceInstancesNumber(racServiceName)):
                    Framework.reportWarning(
                        'Oracle RAC is not running or not all Instances were detected'
                    )
                    continue

                racVersion = servChec.getVersion()
                shortVersion = servChec.getShortVersion()
                listeners = []
                oracles = []
                for ip in parametersDict.keys():
                    hostName = lookuper.lookupByIp(ip) or ' '
                    hostPrimIp = lookuper.getPrimaryIp(ip)
                    actIp = ip

                    if not hostName:
                        Framework.reportError(
                            'Failed to lookup host name of the node. Probably not all nodes were discovered by \"Oracle Listener by Shell\" Job. No RAC CI will be created.'
                        )
                        logger.error(
                            'Failed to lookup host name for node with ip %s . No RAC CI will be created.'
                            % ip)
                        return ObjectStateHolderVector()
                    racNodeNameList.append(hostName)
                    dbSid = parametersDict[actIp]
                    if hostPrimIp:
                        actIp = hostPrimIp
                    hostOSH = modeling.createHostOSH(actIp)
                    OSHVResult.add(hostOSH)
                    listenerOSH = createWeakListener(hostOSH)
                    listeners.append(listenerOSH)
                    oracleOSH = modeling.createDatabaseOSH(
                        'oracle', dbSid, None, actIp, hostOSH, None, None,
                        None, shortVersion, racVersion, shortVersion)
                    instanceNumber = servChec.getDbInstanceNumber(
                        dbSid, racServiceName)
                    if instanceNumber:
                        oracleOSH.setAttribute('oracle_instancenumber',
                                               instanceNumber)
                    oracles.append(oracleOSH)
                racNodeNameList.sort()
                racName = ''
                for nodeName in racNodeNameList:
                    if racName == '':
                        racName = nodeName
                    else:
                        racName += ':' + nodeName
                racOSH = createRacOSH(racName, racInstCount, racServiceName,
                                      racVersion)
                OSHVResult.add(racOSH)
                for listener in listeners:
                    OSHVResult.add(listener)
                    OSHVResult.add(
                        modeling.createLinkOSH('member', racOSH, listener))
                for oracle in oracles:
                    OSHVResult.add(oracle)
                    OSHVResult.add(
                        modeling.createLinkOSH('member', racOSH, oracle))
        finally:
            try:
                shell and shell.closeClient()
            except:
                logger.debugException('')
                logger.error('Unable to close shell')
    except:
        msg = logger.prepareFullStackTrace('')
        errormessages.resolveAndReport(msg, protocol, Framework)
    return OSHVResult
Beispiel #27
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 
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    shell = None
    protocol = Framework.getDestinationAttribute("Protocol")
    listenerName = Framework.getDestinationAttribute("listenerName")
    listenerPath = Framework.getDestinationAttribute("listener_process_path")
    defOraHomes = Framework.getParameter("OracleHomes")
    listenerIp = Framework.getDestinationAttribute("listener_ip")
    listenedIPs = Framework.getTriggerCIDataAsList("listened_ips")

    try:
        try:
            client = Framework.createClient()
            shell = shellutils.ShellUtils(client)

            if listenerPath:
                envConf = UnixOracleEnvConfig(shell)
                if shell.isWinOs():
                    envConf = WindowsOracleEnvConfig(shell)
                envConf.setOracleHomeEnvVar(listenerPath)
            else:
                envConf = EnvConfigurator(shell, defOraHomes)

            if not listenedIPs:
                Framework.reportError("No listened_ips attribute values found.")
                return OSHVResult
            lookuper = LookupManager(listenedIPs)

            serviceToNodesMap = {}
            srvDiscoverer = SrvctlBasedDiscoverer(shell, envConf)
            databases = srvDiscoverer.getDatabases()
            for database in databases:
                instanceAndNodes = srvDiscoverer.getInstancesWithNodes(database)
                if instanceAndNodes:
                    serviceToNodesMap[database] = instanceAndNodes
                    for elem in instanceAndNodes:
                        resolver = DNSResolver(shell, elem.get("Node"))
                        ipAddr = resolver.resolveNSLookup()
                        if not ipAddr:
                            ipAddr = resolver.resolveNSLookupAliasBased()
                            ipAddr = ipAddr and ipAddr[0]
                            try:
                                if not ipAddr:
                                    ipAddr = resolver.resolveHostsFile()
                            except:
                                pass
                        elem["ip"] = ipAddr

            for (serviceName, params) in serviceToNodesMap.items():
                try:
                    listeners = []
                    oracles = []
                    for elem in params:
                        ipAddr = elem.get("ip")
                        if not ipAddr:
                            raise ValueError("One of the Node Ip is not discovered. Can not create full topology.")
                        hostOSH = modeling.createHostOSH(ipAddr)
                        OSHVResult.add(hostOSH)
                        listenerOSH = createWeakListener(hostOSH)
                        if listenerIp == ipAddr:
                            listenerOSH.setStringAttribute("name", listenerName)
                        listeners.append(listenerOSH)
                        oracleOsh = modeling.createDatabaseOSH("oracle", elem["Instance"], None, ipAddr, hostOSH)
                        listeners.append(oracleOsh)
                        oracles.append(oracleOsh)
                    racName = ""
                    nodes = [x["Node"] for x in params if x["Node"]]
                    nodes.sort()
                    racName = ":".join(nodes)
                    racOsh = createRacOSH(racName, len(params), serviceName, None)
                    OSHVResult.add(racOsh)
                    for listener in listeners:
                        OSHVResult.add(listener)
                        OSHVResult.add(modeling.createLinkOSH("member", racOsh, listener))
                    for oracle in oracles:
                        OSHVResult.add(oracle)
                        OSHVResult.add(modeling.createLinkOSH("member", racOsh, oracle))
                except:
                    Framework.reportWarning(
                        'Failed to lookup host name of the node. Probably not all nodes were discovered by "Oracle Listener by Shell" Job. No RAC CI will be created.'
                    )
                    logger.warn("Failed to lookup host name for node with ip. No RAC CI will be created.")
            if not serviceToNodesMap:
                logger.warn("Failed to get information via srvctl. Will use old approach.")
            else:
                return OSHVResult
            # old flow
            tnsConfig = {}
            try:
                tnsConfig = TNSNamesConfig(shell, envConf)
            except:
                logger.debug("Failed to get tnsnames.ora. Trying different home.")
                envConf = EnvConfigurator(shell, defOraHomes)
                oraHome = envConf.findMatchingDefaultOracleHome()
                envConf = UnixOracleEnvConfig(shell)
                envConf.setOracleHomeEnvVar(oraHome)
                tnsConfig = TNSNamesConfig(shell, envConf)

            racParams = tnsConfig.getRacParams()
            servChec = ServiceChecker(shell, envConf, listenerName=listenerName)
            for racServiceName in racParams.keys():
                parametersDict = racParams[racServiceName]
                racNodeNameList = []
                racInstCount = len(parametersDict.keys())

                if (
                    not servChec.isServiceRunning(racServiceName.upper())
                    or racInstCount == 0
                    or racInstCount != int(servChec.getServiceInstancesNumber(racServiceName))
                ):
                    Framework.reportWarning("Oracle RAC is not running or not all Instances were detected")
                    continue

                racVersion = servChec.getVersion()
                shortVersion = servChec.getShortVersion()
                listeners = []
                oracles = []
                for ip in parametersDict.keys():
                    hostName = lookuper.lookupByIp(ip) or " "
                    hostPrimIp = lookuper.getPrimaryIp(ip)
                    actIp = ip

                    if not hostName:
                        Framework.reportError(
                            'Failed to lookup host name of the node. Probably not all nodes were discovered by "Oracle Listener by Shell" Job. No RAC CI will be created.'
                        )
                        logger.error("Failed to lookup host name for node with ip %s . No RAC CI will be created." % ip)
                        return ObjectStateHolderVector()
                    racNodeNameList.append(hostName)
                    dbSid = parametersDict[actIp]
                    if hostPrimIp:
                        actIp = hostPrimIp
                    hostOSH = modeling.createHostOSH(actIp)
                    OSHVResult.add(hostOSH)
                    listenerOSH = createWeakListener(hostOSH)
                    listeners.append(listenerOSH)
                    oracleOSH = modeling.createDatabaseOSH(
                        "oracle", dbSid, None, actIp, hostOSH, None, None, None, shortVersion, racVersion, shortVersion
                    )
                    instanceNumber = servChec.getDbInstanceNumber(dbSid, racServiceName)
                    if instanceNumber:
                        oracleOSH.setAttribute("oracle_instancenumber", instanceNumber)
                    oracles.append(oracleOSH)
                racNodeNameList.sort()
                racName = ""
                for nodeName in racNodeNameList:
                    if racName == "":
                        racName = nodeName
                    else:
                        racName += ":" + nodeName
                racOSH = createRacOSH(racName, racInstCount, racServiceName, racVersion)
                OSHVResult.add(racOSH)
                for listener in listeners:
                    OSHVResult.add(listener)
                    OSHVResult.add(modeling.createLinkOSH("member", racOSH, listener))
                for oracle in oracles:
                    OSHVResult.add(oracle)
                    OSHVResult.add(modeling.createLinkOSH("member", racOSH, oracle))
        finally:
            try:
                shell and shell.closeClient()
            except:
                logger.debugException("")
                logger.error("Unable to close shell")
    except:
        msg = logger.prepareFullStackTrace("")
        errormessages.resolveAndReport(msg, protocol, Framework)
    return OSHVResult
Beispiel #29
0
def infrastructure(client,
                   OSHVResult,
                   Framework,
                   schemaName=None,
                   viewSchemaName=None):
    retOSHs = ArrayList(4)
    retOSHs.add(None)
    retOSHs.add(None)
    retOSHs.add(None)
    retOSHs.add(None)

    systemOSH = ObjectStateHolder('oraclesystem')
    systemOSH.setAttribute('data_name', client.getSid())
    systemOSH.setAttribute('oraclesystem_dbaddress', client.getIpAddress())
    modeling.setAppSystemVendor(systemOSH)

    webServerOSH = None
    nameToHostOSH = HashMap()
    hostToServerOSH = HashMap()
    hostToIpAddress = HashMap()
    databasesOSH = HashMap()

    resultSet = None
    try:
        objs = __assocWithSchemaName(['FND_OAM_APP_SYS_STATUS'], schemaName,
                                     viewSchemaName)
        # query a special table that holds Applications System Status related information
        resultSet = client.executeQuery(
            'SELECT * FROM %s' % objs)  #@@CMD_PERMISION sql protocol execution
    except:
        logger.debugException(
            'SQL query failure. "SELECT * FROM FND_OAM_APP_SYS_STATUS"')
        Framework.reportWarning('No Oracle E-Business Suite components found.')

    if resultSet:
        OSHVResult.add(systemOSH)
        retOSHs.set(0, systemOSH)
    else:
        return None

    while resultSet.next():
        name = resultSet.getString(1)
        dbSid = resultSet.getString(4)
        status = resultSet.getString(6)
        host = resultSet.getString(7)
        port = client.getPort()

        if logger.isDebugEnabled():
            logger.debug('-----------------------------')
            logger.debug('name = ', name)
            logger.debug('status = ', status)
            if host != None:
                logger.debug('host = ', host)
            else:
                logger.debug('skipping Application system with None host')
                continue
            logger.debug('-----------------------------')
        hostOSH = nameToHostOSH.get(host)
        serverOSH = hostToServerOSH.get(host)
        hostIP = hostToIpAddress.get(host)

        if not hostIP:
            hostIP = netutils.getHostAddress(host, host)

        if hostOSH == None and netutils.isValidIp(hostIP):
            hostOSH = modeling.createHostOSH(hostIP)
            OSHVResult.add(hostOSH)
            nameToHostOSH.put(host, hostOSH)
            hostToIpAddress.put(host, hostIP)

        if hostOSH == None:
            logger.warn('Failed to created host [', host, ']')
            continue

        if serverOSH == None:
            serverOSH = modeling.createJ2EEServer('oracleias', hostIP, None,
                                                  hostOSH, host)
            OSHVResult.add(serverOSH)
            hostToServerOSH.put(host, serverOSH)
            serverMemberOSH = modeling.createLinkOSH('member', systemOSH,
                                                     serverOSH)
            OSHVResult.add(serverMemberOSH)
        if name.find('WEB_SERVER') == 0 and host != None:
            webServerOSH = serverOSH
            serverOSH.setBoolAttribute('oracleias_web', 1)
        elif name.find('FORMS_SERVER') == 0 and host != None:
            serverOSH.setBoolAttribute('oracleias_form', 1)
        elif name.find('ADMIN_SERVER') == 0 and host != None:
            serverOSH.setBoolAttribute('oracleias_admin', 1)
        elif name.find('CP_SERVER') == 0 and host != None:
            serverOSH.setBoolAttribute('oracleias_concurrentprocessing', 1)
        elif name.find('DATABASE') == 0 and host != None:
            dbOSH = modeling.createDatabaseOSH('oracle', dbSid, port, hostIP,
                                               hostOSH)
            OSHVResult.add(dbOSH)
            databasesOSH.put(dbSid, dbOSH)
            memberOSH = modeling.createLinkOSH('member', systemOSH, dbOSH)
            OSHVResult.add(memberOSH)
    resultSet.close()
    try:
        systemMetrics(client, systemOSH, webServerOSH, OSHVResult, schemaName,
                      viewSchemaName)
    except:
        logger.debug("Failed to get system metrics")
    retOSHs.set(1, hostToServerOSH)
    retOSHs.set(2, nameToHostOSH)
    retOSHs.set(3, databasesOSH)
    return retOSHs