def process(self, context):
        ConfigBasedPlugin.process(self, context)
        processFolder = self.getProcessFolder(context)
        discoveredVersion = ""
        try:
            discoveredVersion = context.application.getOsh().getAttributeValue("application_version_number")
        except:
            logger.debugException('')
        logger.info("Discovered version is: %s" % discoveredVersion)
        if discoveredVersion and not (discoveredVersion.startswith('9')
                                      or discoveredVersion.startswith('10')):
            raise applications.IgnoreApplicationException('UCMDB is not of a proper version')

        try:
            content = context.client.safecat(processFolder + '../../../conf/cmdb.conf')
        except:
            logger.reportWarning('Failed getting HP uCMDB configuration')
            return

        hostName = self.getPropertyByRegexp(r'dal\.datamodel\.host\.name=(.+)', content)
        dbType = self.getPropertyByRegexp(r'dal\.datamodel\.db\.type=(.+)', content)
        port = self.getPropertyByRegexp(r'dal\.datamodel\.port=(\d+)', content)
        sid = self.getPropertyByRegexp(r'dal\.datamodel\.sid=(\w+)', content)
        if ip_addr.isValidIpAddress(hostName):
            ipAddress = hostName
            ipAddress = ipAddress.encode('utf8').strip()
            hostName = netutils.getHostName(ipAddress)
        if (not sid) and hostName:
            sid = hostName.upper().split('.')[0]
        if hostName and dbType and port and sid:
            hostName = hostName.strip()
            resolver = netutils.IpResolver('', context.framework)
            dbHostIp = resolver.resolveHostIp(hostName)
            if dbHostIp:
                self.reportTopology(context, dbType, port, sid, dbHostIp)
            else:
                logger.warn('Failed resolving DB host "%s" ip address' % hostName)
        else:
            logger.warn('Failed parsing cmdb config file (datamodel part)')

        hostName = self.getPropertyByRegexp(r'dal\.history\.host\.name=(.+)', content)
        dbType = self.getPropertyByRegexp(r'dal\.history\.db\.type=(.+)', content)
        port = self.getPropertyByRegexp(r'dal\.history\.port=(\d+)', content)
        sid = self.getPropertyByRegexp(r'dal\.history\.sid=(\w+)', content)
        if ip_addr.isValidIpAddress(hostName):
            ipAddress = hostName
            ipAddress = ipAddress.encode('utf8').strip()
            hostName = netutils.getHostName(ipAddress)
        if (not sid) and hostName:
            sid = hostName.upper().split('.')[0]
        if hostName and dbType and port and sid:
            hostName = hostName.strip()
            resolver = netutils.IpResolver('', context.framework)
            dbHostIp = resolver.resolveHostIp(hostName)
            if dbHostIp:
                self.reportTopology(context, dbType, port, sid, dbHostIp)
            else:
                logger.warn('Failed resolving DB host "%s" ip address' % hostName)
        else:
            logger.warn('Failed parsing cmdb config file (history part)')
Exemple #2
0
    def getProcesses(self,hostId,sqlServerId,databases,users):
        oshv = ObjectStateHolderVector()
        try:
            logger.debug('get db processes')
            rs = self.connection.getTable("SELECT name as dbname,hostname,program_name,count(*) connection_count,sum(blocked) blocked_sum,net_address,net_library,loginame,nt_username,nt_domain FROM master..sysprocesses a, master..sysdatabases b WHERE a.dbid = b.dbid and hostname is not null and hostname != '' and program_name is not null and program_name != '' group by name,hostname,program_name,net_address,net_library,loginame,nt_username,nt_domain order by dbname, hostname, program_name")

            currentDbOSH = ''
            currentDatabase = ''
            currentHostName = ''
            currentUserName = ''
            clientsCount = 0
            while rs.next():
                try:
                    programName = rs.getString('program_name').strip()
                    hostname = rs.getString('hostname')
                    if hostname == None:
                        continue
                    hostname = string.strip(hostname)
                    hostname = netutils.getHostName(hostname, hostname)

                    dbname = rs.getString('dbname')
                    count = int(rs.getInt('connection_count'))
                    loginName = rs.getString('loginame').strip()
                    #create the dbuser:
                    dbuser = users.get(loginName)
                    #create the use link
                    database = databases.get(dbname)
                    if database is not None:
                        #here we have a bug the user might be NULL
                        #If, e.g, some user like DEVLAB\amqa, logined into the database, while login permissions
                        #are given to the BUILTIN\Administrator, in users map we will have BUILTIN\Administrator,
                        #and we will not find there DEVLAB\amqa although DEVLAB\amqa is in BUILTIN\Administrator group
                        if dbuser is None:
                            logger.debug('could not find user: '******'owner', dbuser, database)
                            oshv.add(owner)

                    if (currentDatabase == dbname) and (currentHostName == hostname) and (currentUserName == programName):
                        clientsCount = clientsCount + count
                    else:
                        self.populateResult(oshv, currentHostName, currentUserName, currentDbOSH, clientsCount)
                        currentDbOSH = database
                        currentDatabase = dbname
                        currentHostName = hostname
                        currentUserName = programName
                        clientsCount = count
                except:
                    logger.debugException(hostId.toString())
            self.populateResult(oshv, currentHostName, currentUserName, currentDbOSH, clientsCount)
            rs.close()
            logger.debug('got processes: ', oshv.size())
        except:
            logger.debugException(hostId.toString())

        return oshv
 def __getHostDnsName(self):
     dnsName = self.hostDnsName
     if not dnsName:
         dnsName = netutils.getHostName(self.hostIp, self.hostIp)
         if dnsName != self.hostIp:
             self.hostDnsName = dnsName
         else:
             dnsName = self.hostIp
     return dnsName
Exemple #4
0
def getServerName(localClient):
    try:
        returnHostName = None
        localClientType = localClient.getClientType()
        ## Try getting the servername from the OS
        if localClientType == 'telnet' or localClientType == 'ssh' or localClientType == 'ntadmin' or localClientType == 'uda':
            osHostName = localClient.executeCmd('hostname')
            if osHostName and len(osHostName) > 0:
                debugPrint(
                    3, '[' + SCRIPT_NAME +
                    ':getServerName] Got OS hostname <%s> for SQL Server using SHELL client'
                    % osHostName)
                returnHostName = osHostName.strip()
        elif localClientType == 'wmi':
            wmiHostNameQuery = 'select Name from Win32_ComputerSystem'
            hostNameResultSet = localClient.executeQuery(wmiHostNameQuery)
            if hostNameResultSet.next():
                osHostName = hostNameResultSet.getString(1)
                if osHostName and len(osHostName) > 0:
                    debugPrint(
                        3, '[' + SCRIPT_NAME +
                        ':getServerName] Got OS hostname <%s> for SQL Server using WMI client'
                        % osHostName)
                    returnHostName = osHostName.strip()
        elif localClientType == 'snmp':
            hostNameResultSet = localClient.executeQuery(
                '1.3.6.1.2.1.1.5,1.3.6.1.2.1.1.6,string')
            while hostNameResultSet.next():
                osHostName = hostNameResultSet.getString(2)
                if osHostName and len(osHostName) > 0:
                    debugPrint(
                        3, '[' + SCRIPT_NAME +
                        ':getServerName] Got OS hostname <%s> for SQL Server using SNMP client'
                        % osHostName)
                    returnHostName = osHostName.strip()
        ## If we don't have a name yet, try DNS
        if returnHostName == None or returnHostName == '' or len(
                returnHostName) < 1:
            dnsName = netutils.getHostName(localClient.getIpAddress())
            if dnsName and len(dnsName) > 0 and dnsName.find('.'):
                debugPrint(
                    3, '[' + SCRIPT_NAME +
                    ':getServerName] Got DNS name <%s> for SQL Server' %
                    dnsName)
                hostName = dnsName[:dnsName.find('.')]
                if hostName and len(hostName) > 0:
                    debugPrint(
                        3, '[' + SCRIPT_NAME +
                        ':getServerName] Got host name <%s> for SQL Server from DNS name'
                        % hostName)
                    returnHostName = hostName
        return returnHostName
    except:
        excInfo = logger.prepareJythonStackTrace('')
        debugPrint('[' + SCRIPT_NAME +
                   ':getServerName] Exception: <%s>' % excInfo)
        pass
 def __getHostDnsName(self):
     dnsName = self.hostDnsName
     if not dnsName:
         dnsName = netutils.getHostName(self.hostIp, self.hostIp)
         if dnsName != self.hostIp:
             self.hostDnsName = dnsName
         else:
             dnsName = self.hostIp
     return dnsName
    def process(self, context):
        self.shell = context.client
        applicationOsh = context.application.getOsh()
        applicationServerName = str(applicationOsh.getAttributeValue('name'))
        applicationServerIp = str(applicationOsh.getAttributeValue('application_ip'))
        applicationProfile = str(applicationOsh.getAttributeValue('sap_instance_profile'))
        logger.info('SAP ABAP Application Server Name: ', applicationServerName)
        logger.info('SAP ABAP Application Server application_ip: ', applicationServerIp)
        logger.info('SAP ABAP Application Server Profile: ', applicationProfile)

        # SAP ABAP Application Server CIT should be created with Name attribute in format
        # - ${HOSTNAME}_${SAPSYSTEMNAME}_${INSTANCE_NUMBER}

        # get the hostname from file
        hostnameF = None
        # get the hostname from command
        hostnameC = None
        # get the hostname from ip address
        hostname = None

        underLines = applicationServerName.count('_')
        serverName = applicationServerName.split('_', underLines - 1)

        fileContent = sap_discoverer_by_shell.read_pf(self.shell, applicationProfile)
        if fileContent and fileContent[1]:
            hostnameF = fileContent[1].get('SAPLOCALHOST') or fileContent[1].get(u'SAPLOCALHOST')
        if hostnameF:
            logger.info('SAP ABAP Application Server hostname, fetch from profile: ', hostnameF)
            applicationServerName = str(hostnameF).lower() + '_' + serverName[-1]
            applicationOsh.setStringAttribute('name', applicationServerName)
            return
        
        # if there is no SAPLOCALHOST from profile, try to get the hostname from command
        try:
            hostnameC = str(self.shell.execCmd('hostname'))
            if hostnameC:
                applicationServerName = hostnameC.lower() + '_' + serverName[-1]
                applicationOsh.setStringAttribute('name', applicationServerName)
                logger.info('SAP ABAP Application Server hostname, get from command: ', hostnameC)
                return
        except:
            logger.debug('cannot get hostname by command')

        # if cannot get the hostname by command, try to resolve it by IP address
        if applicationServerIp:
            hostname = netutils.getHostName(applicationServerIp)

        if hostname:
            applicationServerName = hostname.lower() + '_' + serverName[-1]
            logger.info('SAP ABAP Application Server hostname, resolved by ip: ', hostname)
            applicationOsh.setStringAttribute('name', applicationServerName)
        else:
            logger.debug('there is no valid ip address or hostname')
    def process(self, context):
        self.shell = context.client
        applicationOsh = context.application.getOsh()
        applicationServerName = str(applicationOsh.getAttributeValue("name"))
        applicationServerIp = str(applicationOsh.getAttributeValue("application_ip"))
        applicationProfile = str(applicationOsh.getAttributeValue("sap_instance_profile"))
        logger.info("SAP ABAP Application Server Name: ", applicationServerName)
        logger.info("SAP ABAP Application Server application_ip: ", applicationServerIp)
        logger.info("SAP ABAP Application Server Profile: ", applicationProfile)

        # SAP ABAP Application Server CIT should be created with Name attribute in format
        # - ${HOSTNAME}_${SAPSYSTEMNAME}_${INSTANCE_NUMBER}

        # get the hostname from file
        hostnameF = None
        # get the hostname from command
        hostnameC = None
        # get the hostname from ip address
        hostname = None

        underLines = applicationServerName.count("_")
        serverName = applicationServerName.split("_", underLines - 1)

        fileContent = sap_discoverer_by_shell.read_pf(self.shell, applicationProfile)
        if fileContent and fileContent[1]:
            hostnameF = fileContent[1].get("SAPLOCALHOST") or fileContent[1].get(u"SAPLOCALHOST")
        if hostnameF:
            logger.info("SAP ABAP Application Server hostname, fetch from profile: ", hostnameF)
            applicationServerName = str(hostnameF).lower() + "_" + serverName[-1]
            applicationOsh.setStringAttribute("name", applicationServerName)
            return

        # if there is no SAPLOCALHOST from profile, try to get the hostname from command
        try:
            hostnameC = str(self.shell.execCmd("hostname"))
            if hostnameC:
                applicationServerName = hostnameC.lower() + "_" + serverName[-1]
                applicationOsh.setStringAttribute("name", applicationServerName)
                logger.info("SAP ABAP Application Server hostname, get from command: ", hostnameC)
                return
        except:
            logger.debug("cannot get hostname by command")

        # if cannot get the hostname by command, try to resolve it by IP address
        if applicationServerIp:
            hostname = netutils.getHostName(applicationServerIp)

        if hostname:
            applicationServerName = hostname.lower() + "_" + serverName[-1]
            logger.info("SAP ABAP Application Server hostname, resolved by ip: ", hostname)
            applicationOsh.setStringAttribute("name", applicationServerName)
        else:
            logger.debug("there is no valid ip address or hostname")
def processNetDeviceInfo(ipAddress, netDeviceName, ipAddressList, netDeviceOSHV, allowDnsLookup):
    try:
        netDeviceOSH = ipOSH = None
        ciscoworks_utils.debugPrint(3, '[' + SCRIPT_NAME + ':processNetDeviceInfo] Got Net Device <%s>' % netDeviceName)

        ## Check if this NetDevice is already in the OSHV
        netDeviceOSH = ciscoworks_utils.getCiByAttributesFromOSHV(netDeviceOSHV, 'netdevice', {'data_externalid':netDeviceName})
        if netDeviceOSH:
            ciscoworks_utils.debugPrint(2, '[' + SCRIPT_NAME + ':processNetDeviceInfo] CI for Net Device <%s> exists in UCMDB' % netDeviceName)
        else:
            ## Try and get a DNS name for this node
            netDeviceDnsName = None
            if allowDnsLookup and ipAddress and netutils.isValidIp(ipAddress):
                netDeviceDnsName = netutils.getHostName(ipAddress)
                ciscoworks_utils.debugPrint(4, '[' + SCRIPT_NAME + ':processNetDeviceInfo] Got DNS name <%s> for Net Device <%s> using IP <%s>' % (netDeviceDnsName, netDeviceName, ipAddress))

            ## Discard IP if this is a duplicate
            if ipAddress and netutils.isValidIp(ipAddress) and ipAddress in ipAddressList:
                logger.debug('Ignoring duplicate IP <%s> on Net Device <%s>...' % (ipAddress, netDeviceName))
            else:
                ipAddressList.append(ipAddress)

            ## Check for a valid IP
            if ipAddress and netutils.isValidIp(ipAddress):
                ipOSH = modeling.createIpOSH(ipAddress, None, netDeviceDnsName, None)
            else:
                logger.debug('Ignoring duplicate IP <%s>...' % netDeviceName)
            ## If an IP is available, build a Net Device CI
            if ipOSH:
                ciscoworks_utils.debugPrint(3, '[' + SCRIPT_NAME + ':processNetDeviceInfo] Creating CI for Net Device <%s> with <%s> as key' % (netDeviceName, ipAddress))
                netDeviceOSH = modeling.createHostOSH(ipAddress, 'netdevice')
                netDeviceOSH.setAttribute('data_externalid', netDeviceName)
                if netDeviceName and not netutils.isValidIp(netDeviceName):
                    netDeviceOSH.setAttribute('name', netDeviceName)
                if netDeviceDnsName:
                    netDeviceOSH.setAttribute('primary_dns_name', netDeviceDnsName)
                netDeviceOSHV.add(netDeviceOSH)
        return (netDeviceOSH, ipOSH)
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.warn('[' + SCRIPT_NAME + ':processNetDeviceInfo] Exception: <%s>' % excInfo)
        pass
def getServerName(localClient):
    try:
        returnHostName = None
        localClientType = localClient.getClientType()
        ## Try getting the servername from the OS
        if localClientType == 'telnet' or localClientType == 'ssh' or localClientType == 'ntadmin' or localClientType == 'uda':
            osHostName = localClient.executeCmd('hostname')
            if osHostName and len(osHostName) > 0:
                debugPrint(3, '[' + SCRIPT_NAME + ':getServerName] Got OS hostname <%s> for SQL Server using SHELL client' % osHostName)
                returnHostName = osHostName.strip()
        elif localClientType == 'wmi':
            wmiHostNameQuery = 'select Name from Win32_ComputerSystem'
            hostNameResultSet = localClient.executeQuery(wmiHostNameQuery)
            if hostNameResultSet.next():
                osHostName = hostNameResultSet.getString(1)
                if osHostName and len(osHostName) > 0:
                    debugPrint(3, '[' + SCRIPT_NAME + ':getServerName] Got OS hostname <%s> for SQL Server using WMI client' % osHostName)
                    returnHostName = osHostName.strip()
        elif localClientType == 'snmp':
            hostNameResultSet = localClient.executeQuery('1.3.6.1.2.1.1.5,1.3.6.1.2.1.1.6,string')
            while hostNameResultSet.next():
                osHostName = hostNameResultSet.getString(2)
                if osHostName and len(osHostName) > 0:
                    debugPrint(3, '[' + SCRIPT_NAME + ':getServerName] Got OS hostname <%s> for SQL Server using SNMP client' % osHostName)
                    returnHostName = osHostName.strip()
        ## If we don't have a name yet, try DNS
        if returnHostName == None or returnHostName == '' or len(returnHostName) < 1:
            dnsName = netutils.getHostName(localClient.getIpAddress())
            if dnsName and len(dnsName) > 0 and dnsName.find('.'):
                debugPrint(3, '[' + SCRIPT_NAME + ':getServerName] Got DNS name <%s> for SQL Server' % dnsName)
                hostName = dnsName[:dnsName.find('.')]
                if hostName and len(hostName) > 0:
                    debugPrint(3, '[' + SCRIPT_NAME + ':getServerName] Got host name <%s> for SQL Server from DNS name' % hostName)
                    returnHostName =  hostName
        return returnHostName
    except:
        excInfo = logger.prepareJythonStackTrace('')
        debugPrint('[' + SCRIPT_NAME + ':getServerName] Exception: <%s>' % excInfo)
        pass
Exemple #10
0
def getServerName(localClient):
    try:
        returnHostName = None
        localClientType = localClient.getClientType()
        ## Try getting the servername from the OS
        if (
            localClientType == "telnet"
            or localClientType == "ssh"
            or localClientType == "ntadmin"
            or localClientType == "uda"
        ):
            osHostName = localClient.executeCmd("hostname")
            if osHostName and len(osHostName) > 0:
                debugPrint(
                    3,
                    "["
                    + SCRIPT_NAME
                    + ":getServerName] Got OS hostname <%s> for SQL Server using SHELL client" % osHostName,
                )
                returnHostName = osHostName.strip()
        elif localClientType == "wmi":
            wmiHostNameQuery = "select Name from Win32_ComputerSystem"
            hostNameResultSet = localClient.executeQuery(wmiHostNameQuery)
            if hostNameResultSet.next():
                osHostName = hostNameResultSet.getString(1)
                if osHostName and len(osHostName) > 0:
                    debugPrint(
                        3,
                        "["
                        + SCRIPT_NAME
                        + ":getServerName] Got OS hostname <%s> for SQL Server using WMI client" % osHostName,
                    )
                    returnHostName = osHostName.strip()
        elif localClientType == "snmp":
            hostNameResultSet = localClient.executeQuery("1.3.6.1.2.1.1.5,1.3.6.1.2.1.1.6,string")
            while hostNameResultSet.next():
                osHostName = hostNameResultSet.getString(2)
                if osHostName and len(osHostName) > 0:
                    debugPrint(
                        3,
                        "["
                        + SCRIPT_NAME
                        + ":getServerName] Got OS hostname <%s> for SQL Server using SNMP client" % osHostName,
                    )
                    returnHostName = osHostName.strip()
        ## If we don't have a name yet, try DNS
        if returnHostName == None or returnHostName == "" or len(returnHostName) < 1:
            dnsName = netutils.getHostName(localClient.getIpAddress())
            if dnsName and len(dnsName) > 0 and dnsName.find("."):
                debugPrint(3, "[" + SCRIPT_NAME + ":getServerName] Got DNS name <%s> for SQL Server" % dnsName)
                hostName = dnsName[: dnsName.find(".")]
                if hostName and len(hostName) > 0:
                    debugPrint(
                        3,
                        "["
                        + SCRIPT_NAME
                        + ":getServerName] Got host name <%s> for SQL Server from DNS name" % hostName,
                    )
                    returnHostName = hostName
        return returnHostName
    except:
        excInfo = logger.prepareJythonStackTrace("")
        debugPrint("[" + SCRIPT_NAME + ":getServerName] Exception: <%s>" % excInfo)
        pass
def processNodeInfo(ipAddress, macAddress, nodeName, subnetMask, ipAddressList, macAddressList, nodeOshDict, allowDnsLookup):
    try:
        nodeOSH = interfaceOSH = ipOSH = None
        ## Try and get a DNS name for this node
        nodeDnsName = None
        if allowDnsLookup and ipAddress and netutils.isValidIp(ipAddress):
            nodeDnsName = netutils.getHostName(ipAddress)
            ciscoworks_utils.debugPrint(3, '[' + SCRIPT_NAME + ':processNodeInfo] Got DNS name <%s> for Node <%s> using IP <%s>' % (nodeDnsName, nodeName, ipAddress))
            if nodeDnsName:
                nodeName = nodeDnsName

        ## Discard IP if this is a duplicate
        if ipAddress and netutils.isValidIp(ipAddress) and ipAddress in ipAddressList:
            logger.debug('Ignoring duplicate IP <%s> on Node <%s>...' % (ipAddress, nodeName))
            ipAddress = None
        else:
            ipAddressList.append(ipAddress)

        ## Set the real name of the netDevice
        nodeRealName = nodeName
        if nodeName and netutils.isValidIp(nodeName):
            nodeRealName = ''

        ## Build a host key and create OSHs
        ## Check for and clean up MAC
        macAddy = None
        if macAddress:
            macAddy = netutils.parseMac(macAddress)
            ## Check for duplicate MAC addresses
            if macAddy in macAddressList:
                logger.debug('Ignoring duplicate MAC Address <%s> on Node <%s>...' % (macAddy, nodeName))
                macAddy = None
            else:
                macAddressList.append(macAddy)
            if netutils.isValidMac(macAddy):
                ciscoworks_utils.debugPrint(3, '[' + SCRIPT_NAME + ':processNodeInfo] Got MAC Address <%s> for Node <%s>' % (macAddy, nodeName))
                nodeOSH = modeling.createCompleteHostOSH('node', macAddy, None, nodeName)
                interfaceOSH = modeling.createInterfaceOSH(macAddy, nodeOSH)
            else:
                ciscoworks_utils.debugPrint(3, '[' + SCRIPT_NAME + ':processNodeInfo] Got invalid MAC Address <%s> for Node <%s>' % (macAddress, nodeName))
                macAddy = None

        ## Check for a valid IP
        if ipAddress and netutils.isValidIp(ipAddress):
            subnetMask = None
            if subnetMask:
                subnetMask = netutils.parseNetMask(subnetMask)
            ipOSH = modeling.createIpOSH(ipAddress, subnetMask, ipAddress, None)
            ## Use IP as a host key if a MAC is not available
            if not macAddy:
                nodeOSH = modeling.createHostOSH(ipAddress, 'node', None, nodeRealName)
        else:
            logger.debug('IP address not available for Node <%s> with MAC address <%s>' % (nodeName, macAddress))

        if not nodeOSH:
            logger.debug('Ignoring Node <%s> because a valid IP/MAC address was not found for it...' % nodeName)

        return (nodeOSH, interfaceOSH, ipOSH)
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.warn('[' + SCRIPT_NAME + ':processNodeInfo] Exception: <%s>' % excInfo)
        pass
Exemple #12
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    ips      = Framework.getTriggerCIDataAsList('ip_address')
    ip_ids    = Framework.getTriggerCIDataAsList('ip_id')
    host_id    = Framework.getTriggerCIData('host_id')
    host_name = Framework.getTriggerCIData('host_name')
    hostOSH = modeling.createOshByCmdbIdString('node', host_id)
    dnsServers = Framework.getParameter('dnsServers') or None
    localShell = None
    
    if dnsServers:
        dnsServers = [dnsServer for dnsServer in dnsServers.split(',') if dnsServer and dnsServer.strip()] or None
    
    if dnsServers:
        localShell = shellutils.ShellUtils(Framework.createClient(ClientsConsts.LOCAL_SHELL_PROTOCOL_NAME))        

    smallIp = '255.255.255.255'
    smallIpDns = None
    smallPublicIpDns = None
    primary_dns_name_candidates = []
    index=0
    for ip in ips:

        ip_id    = ip_ids[index]
        index    = index+1

        if dnsServers:
            dnsName = resolveHostNameByDnsList(ip,localShell,dnsServers)
        else:
            dnsName = netutils.getHostName(ip, None)
        logger.debug('dns, %s:%s'%(ip,dnsName))
        if dnsName == None:
            continue
        else:
            # Set ip DNS by dnsName
            ipOSH = modeling.createOshByCmdbIdString('ip_address', ip_id)
            ipOSH.setAttribute('name', ip)
            ipOSH.setAttribute('authoritative_dns_name', dnsName)
            containmentLink = modeling.createLinkOSH('containment',hostOSH,ipOSH)
            OSHVResult.add(containmentLink)
            OSHVResult.add(ipOSH)

            if host_name and dnsName.split('.')[0] == host_name:    #share same short name
                primary_dns_name_candidates.append(dnsName)

            if netutils.convertIpToInt(ip) < netutils.convertIpToInt(smallIp):
                smallIp = ip
                smallIpDns = dnsName
                if not netutils.isPrivateIp(ip):
                    smallPublicIpDns = dnsName

    logger.debug("Primary candidates:", primary_dns_name_candidates)
    if smallPublicIpDns:
        logger.debug("Set public dns", smallPublicIpDns)
        smallIpDns = smallPublicIpDns
    if smallIpDns and (not primary_dns_name_candidates or smallIpDns in primary_dns_name_candidates):
        # Set host DNS smallIpDns
        logger.debug("Set host DNS smallIpDns:", smallIpDns)
        hostOSH.setAttribute('primary_dns_name', smallIpDns)
        OSHVResult.add(hostOSH)
    else:
        if primary_dns_name_candidates:
            #if there are multiple candidates, we can only choose one without any prefer
            logger.debug("Set first primary dns:", primary_dns_name_candidates[0])
            hostOSH.setAttribute('primary_dns_name', primary_dns_name_candidates[0])
            OSHVResult.add(hostOSH)

    if not OSHVResult.size():
        logger.reportError("Cannot resolve host from DNS")

    if localShell is not None:
        try:
            localShell.close()
            localShell = None
        except:
            pass
    return OSHVResult
Exemple #13
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    ips = Framework.getTriggerCIDataAsList('ip_address')
    ip_ids = Framework.getTriggerCIDataAsList('ip_id')
    host_id = Framework.getTriggerCIData('host_id')
    host_name = Framework.getTriggerCIData('host_name')
    hostOSH = modeling.createOshByCmdbIdString('node', host_id)
    dnsServers = Framework.getParameter('dnsServers') or None
    localShell = None

    if dnsServers:
        dnsServers = [
            dnsServer for dnsServer in dnsServers.split(',')
            if dnsServer and dnsServer.strip()
        ] or None

    if dnsServers:
        localShell = shellutils.ShellUtils(
            Framework.createClient(ClientsConsts.LOCAL_SHELL_PROTOCOL_NAME))

    smallIp = '255.255.255.255'
    smallIpDns = None
    smallPublicIpDns = None
    primary_dns_name_candidates = []
    index = 0
    for ip in ips:

        ip_id = ip_ids[index]
        index = index + 1

        if dnsServers:
            dnsName = resolveHostNameByDnsList(ip, localShell, dnsServers)
        else:
            dnsName = netutils.getHostName(ip, None)
        logger.debug('dns, %s:%s' % (ip, dnsName))
        if dnsName == None:
            continue
        else:
            # Set ip DNS by dnsName
            ipOSH = modeling.createOshByCmdbIdString('ip_address', ip_id)
            ipOSH.setAttribute('name', ip)
            ipOSH.setAttribute('authoritative_dns_name', dnsName)
            containmentLink = modeling.createLinkOSH('containment', hostOSH,
                                                     ipOSH)
            OSHVResult.add(containmentLink)
            OSHVResult.add(ipOSH)

            if host_name and dnsName.split(
                    '.')[0] == host_name:  #share same short name
                primary_dns_name_candidates.append(dnsName)

            if netutils.convertIpToInt(ip) < netutils.convertIpToInt(smallIp):
                smallIp = ip
                smallIpDns = dnsName
                if not netutils.isPrivateIp(ip):
                    smallPublicIpDns = dnsName

    logger.debug("Primary candidates:", primary_dns_name_candidates)
    if smallPublicIpDns:
        logger.debug("Set public dns", smallPublicIpDns)
        smallIpDns = smallPublicIpDns
    if smallIpDns and (not primary_dns_name_candidates
                       or smallIpDns in primary_dns_name_candidates):
        # Set host DNS smallIpDns
        logger.debug("Set host DNS smallIpDns:", smallIpDns)
        hostOSH.setAttribute('primary_dns_name', smallIpDns)
        OSHVResult.add(hostOSH)
    else:
        if primary_dns_name_candidates:
            #if there are multiple candidates, we can only choose one without any prefer
            logger.debug("Set first primary dns:",
                         primary_dns_name_candidates[0])
            hostOSH.setAttribute('primary_dns_name',
                                 primary_dns_name_candidates[0])
            OSHVResult.add(hostOSH)

    if not OSHVResult.size():
        logger.reportError("Cannot resolve host from DNS")

    if localShell is not None:
        try:
            localShell.close()
            localShell = None
        except:
            pass
    return OSHVResult
    def process(self, context):
        ConfigBasedPlugin.process(self, context)
        processFolder = self.getProcessFolder(context)
        discoveredVersion = ""
        try:
            discoveredVersion = context.application.getOsh().getAttributeValue(
                "application_version_number")
        except:
            logger.debugException('')
        logger.info("Discovered version is: %s" % discoveredVersion)
        if discoveredVersion and not (discoveredVersion.startswith('9')
                                      or discoveredVersion.startswith('10')):
            raise applications.IgnoreApplicationException(
                'UCMDB is not of a proper version')

        try:
            content = context.client.safecat(processFolder +
                                             '../../../conf/cmdb.conf')
        except:
            logger.reportWarning('Failed getting HP uCMDB configuration')
            return

        hostName = self.getPropertyByRegexp(r'dal\.datamodel\.host\.name=(.+)',
                                            content)
        dbType = self.getPropertyByRegexp(r'dal\.datamodel\.db\.type=(.+)',
                                          content)
        port = self.getPropertyByRegexp(r'dal\.datamodel\.port=(\d+)', content)
        sid = self.getPropertyByRegexp(r'dal\.datamodel\.sid=(\w+)', content)
        if ip_addr.isValidIpAddress(hostName):
            ipAddress = hostName
            ipAddress = ipAddress.encode('utf8').strip()
            hostName = netutils.getHostName(ipAddress)
        if (not sid) and hostName:
            sid = hostName.upper().split('.')[0]
        if hostName and dbType and port and sid:
            hostName = hostName.strip()
            resolver = netutils.IpResolver('', context.framework)
            dbHostIp = resolver.resolveHostIp(hostName)
            if dbHostIp:
                self.reportTopology(context, dbType, port, sid, dbHostIp)
            else:
                logger.warn('Failed resolving DB host "%s" ip address' %
                            hostName)
        else:
            logger.warn('Failed parsing cmdb config file (datamodel part)')

        hostName = self.getPropertyByRegexp(r'dal\.history\.host\.name=(.+)',
                                            content)
        dbType = self.getPropertyByRegexp(r'dal\.history\.db\.type=(.+)',
                                          content)
        port = self.getPropertyByRegexp(r'dal\.history\.port=(\d+)', content)
        sid = self.getPropertyByRegexp(r'dal\.history\.sid=(\w+)', content)
        if ip_addr.isValidIpAddress(hostName):
            ipAddress = hostName
            ipAddress = ipAddress.encode('utf8').strip()
            hostName = netutils.getHostName(ipAddress)
        if (not sid) and hostName:
            sid = hostName.upper().split('.')[0]
        if hostName and dbType and port and sid:
            hostName = hostName.strip()
            resolver = netutils.IpResolver('', context.framework)
            dbHostIp = resolver.resolveHostIp(hostName)
            if dbHostIp:
                self.reportTopology(context, dbType, port, sid, dbHostIp)
            else:
                logger.warn('Failed resolving DB host "%s" ip address' %
                            hostName)
        else:
            logger.warn('Failed parsing cmdb config file (history part)')