예제 #1
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()

    localHostId = Framework.getDestinationAttribute('localHostId')
    remoteIds = Framework.getTriggerCIDataAsList('clusteredUcmdbIds')
    localSoftwareId = Framework.getDestinationAttribute('localSoftwareId')
    clusteredContainers = Framework.getTriggerCIDataAsList(
        'clusteredContainer')
    softwareName = Framework.getDestinationAttribute('softwareName')
    className = Framework.getDestinationAttribute('className')
    discProdName = Framework.getDestinationAttribute('discProdName')
    productName = Framework.getDestinationAttribute('productName')
    ipServiceEndpointIds = Framework.getTriggerCIDataAsList(
        'ipServiceEndpointIds') or []

    for remoteIndex in xrange(len(remoteIds)):

        remoteId = remoteIds[remoteIndex]
        clusteredContainer = None
        try:
            clusteredContainer = clusteredContainers[remoteIndex]
        except:
            logger.debug('Clustered software is related to a single CRG')
            clusteredContainer = clusteredContainers[0]
        if not clusteredContainer:
            raise ValueError(
                'Failed to detect Clustered Resource Group for Clustered Software'
            )
        logger.debug('Working with remote Id %s and clustered Container %s' %
                     (remoteId, clusteredContainer))
        vector = ObjectStateHolderVector()

        softwareOsh = modeling.createOshByCmdbId(className, localSoftwareId)
        hostOsh = modeling.createOshByCmdbId('cluster_resource_group',
                                             clusteredContainer)
        softwareOsh.setContainer(hostOsh)
        softwareOsh.setStringAttribute('name', softwareName)

        if discProdName and discProdName != 'NA':
            softwareOsh.setStringAttribute('discovered_product_name',
                                           discProdName)

        if productName and productName != 'NA':
            softwareOsh.setStringAttribute('product_name', productName)

        for ipServiceEndpointId in ipServiceEndpointIds:
            logger.debug("ip service endpoint id:", ipServiceEndpointId)
            if not ipServiceEndpointId:
                continue
            iseOsh = modeling.createOshByCmdbId('ip_service_endpoint',
                                                ipServiceEndpointId)
            iseOsh.setContainer(hostOsh)
            vector.add(iseOsh)
        vector.add(hostOsh)
        vector.add(softwareOsh)
        OSHVResult.addAll(vector)
    return OSHVResult
예제 #2
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    
    localHostId = Framework.getDestinationAttribute('localHostId')
    remoteIds = Framework.getTriggerCIDataAsList('clusteredUcmdbIds')
    localSoftwareId = Framework.getDestinationAttribute('localSoftwareId')
    clusteredContainers = Framework.getTriggerCIDataAsList('clusteredContainer')
    softwareName = Framework.getDestinationAttribute('softwareName')
    className = Framework.getDestinationAttribute('className')  
    discProdName = Framework.getDestinationAttribute('discProdName')
    productName = Framework.getDestinationAttribute('productName')
    ipServiceEndpointIds = Framework.getTriggerCIDataAsList('ipServiceEndpointIds') or []

    for remoteIndex in xrange(len(remoteIds)):

        remoteId = remoteIds[remoteIndex]
        clusteredContainer = None
        try:
            clusteredContainer = clusteredContainers[remoteIndex]
        except:
            logger.debug('Clustered software is related to a single CRG')
            clusteredContainer = clusteredContainers[0]
        if not clusteredContainer:
            raise ValueError('Failed to detect Clustered Resource Group for Clustered Software')
        logger.debug('Working with remote Id %s and clustered Container %s' % (remoteId, clusteredContainer))
        vector = ObjectStateHolderVector()
        
        softwareOsh = modeling.createOshByCmdbId(className, localSoftwareId)
        hostOsh = modeling.createOshByCmdbId('cluster_resource_group', clusteredContainer)
        softwareOsh.setContainer(hostOsh)
        softwareOsh.setStringAttribute('name', softwareName)
        
        if discProdName and discProdName != 'NA':
            softwareOsh.setStringAttribute('discovered_product_name', discProdName)
        
        if productName and productName != 'NA':
            softwareOsh.setStringAttribute('product_name', productName)

        for ipServiceEndpointId in ipServiceEndpointIds:
            logger.debug("ip service endpoint id:", ipServiceEndpointId)
            if not ipServiceEndpointId:
                continue
            iseOsh = modeling.createOshByCmdbId('ip_service_endpoint', ipServiceEndpointId)
            iseOsh.setContainer(hostOsh)
            vector.add(iseOsh)
        vector.add(hostOsh)
        vector.add(softwareOsh)
        OSHVResult.addAll(vector)
    return OSHVResult
예제 #3
0
def createOshFromId(ciDict, id, ciClass = None):
    osh = None
    object = ciDict[id]
    # create the container osh
    if object != None:
        id = object[0]
        type = object[1]
        props = object[2]
        ciid = object[3]
        if type in host_types:
            real_ci_class = ciClass or type
            osh  =  modeling.createOshByCmdbId(real_ci_class, ciid)
        else:    
            osh = ObjectStateHolder(type)
        if props != None:
            for prop in props:
                if prop[1] == 'Integer':
                    osh.setIntegerAttribute(prop[0], prop[3]) 
                elif prop[1] == 'Long': 
                    osh.setLongAttribute(prop[0], prop[3])
                elif prop[1] == 'Enum':
                    osh.setEnumAttribute(prop[0], int(prop[3]))
                else:
                    osh.setAttribute(prop[0], prop[3])              
    return osh
예제 #4
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    shell = None
    protocol = Framework.getDestinationAttribute('Protocol')
    switchId = Framework.getDestinationAttribute('hostId')
    print "Switch id %s" % switchId
    errorMessage = None
    try:
        client = Framework.createClient()
        try:
            shellFactory = shellutils.ShellFactory()
            shell = shellFactory.createShell(client)
            switchOsh = modeling.createOshByCmdbId('switch', switchId)
            discoverer = NexusDiscoverer(Framework, shell, '', '', '', '')
            discoverer.discoverInterfacesAndIps()
            interfaces_dict = discoverer.hostDataObject.interfaces
            ports_map = parsePorts(interfaces_dict.values())
            vlan_discoverer = layer2_shell_discoverer.VlanDiscoverer(shell)
            vlans = vlan_discoverer.discoverVlans()

            layer2_discoverer = layer2_shell_discoverer.Layer2Discoverer(shell)
            remote_peers_map = layer2_discoverer.discover()

            OSHVResult.addAll(layer2.reportTopology(switchOsh, interfaces_dict, vlans, remote_peers_map, ports_map))
            
        finally:
            try:
                shell and shell.closeClient()
            except:
                logger.debugException('')
                logger.error('Unable to close shell')
    except JException, ex:
        errorMessage = ex.getMessage()
예제 #5
0
def createOshFromId(ciDict, id, ciClass=None):
    osh = None
    object = ciDict[id]
    # create the container osh
    if object != None:
        id = object[0]
        type = object[1]
        props = object[2]
        ciid = object[3]
        if type in host_types:
            real_ci_class = ciClass or type
            osh = modeling.createOshByCmdbId(real_ci_class, ciid)
        else:
            osh = ObjectStateHolder(type)
        if props != None:
            for prop in props:
                if prop[1] == 'Integer':
                    osh.setIntegerAttribute(prop[0], prop[3])
                elif prop[1] == 'Long':
                    osh.setLongAttribute(prop[0], prop[3])
                elif prop[1] == 'Enum':
                    osh.setEnumAttribute(prop[0], int(prop[3]))
                else:
                    osh.setAttribute(prop[0], prop[3])
    return osh
예제 #6
0
def triggered_on_ipse_only(client, framework, dns_resolver, cred_id, ip, dbname, port, ipse_id):
    db_oshs, oshs, warnings = _discover(client, framework, dns_resolver, cred_id, dbname, port)

    config = DiscoveryConfig(framework, cred_id)

    reporter = db2_topology.Reporter()

    link_reporter = db2_topology.LinkReporter()

    node_osh = modeling.createOshByCmdbId('node', config.host_id)
    oshs.append(node_osh)

    instance = db.DatabaseServer(ip, port)
    inst_osh, _, _, vector = reporter.reportServerAndDatabases(instance, node_osh)
    oshs.extend(vector)

    alias_osh = reporter.reportDbAlias(dbname, inst_osh)
    db2_topology.Builder.update_credential_id(alias_osh, cred_id)
    oshs.append(alias_osh)

    if db_oshs:
        db_osh = db_oshs.pop()
        realization_osh = link_reporter.report_realization(alias_osh, db_osh)
        oshs.append(realization_osh)

    return oshs, warnings
def reportProcessToPort(hostId, processes, endpoints):
    if not (processes and endpoints):
        return 
    vector = ObjectStateHolderVector()
    hostOsh = modeling.createOshByCmdbId('node', hostId)
    vector.add(hostOsh)
    proc_builder = ProcessBuilder()
    key_to_endpoints_map = {}
    [ key_to_endpoints_map.update({x.getKey(): x.getEndpoints()}) for x in endpoints ]
    for process in processes:
        processOsh = proc_builder.buildProcessOsh(process)
        processOsh.setContainer(hostOsh)
        vector.add(processOsh)
        remotes = key_to_endpoints_map.get(process.getPid())
        if remotes:
            for remote in remotes:
                if not netutils.isValidIp(remote.getAddress()):
                    logger.debug(remote, ' is not a valid ip')
                    continue
                builder = netutils.ServiceEndpointBuilder()
                reporter = netutils.EndpointReporter(builder)
                nodeOsh = reporter.reportHostFromEndpoint(remote)
                endpointOsh = reporter.reportEndpoint(remote, nodeOsh)
                linkOsh = modeling.createLinkOSH('client_server', processOsh, endpointOsh)
                linkOsh.setStringAttribute('clientserver_protocol', 'tcp')
                vector.add(nodeOsh)
                vector.add(endpointOsh)
                vector.add(linkOsh)
    return vector
예제 #8
0
def triggered_on_ipse_only(client, framework, dns_resolver, cred_id, ip,
                           dbname, port, ipse_id):
    db_oshs, oshs, warnings = _discover(client, framework, dns_resolver,
                                        cred_id, dbname, port)

    config = DiscoveryConfig(framework, cred_id)

    reporter = db2_topology.Reporter()

    link_reporter = db2_topology.LinkReporter()

    node_osh = modeling.createOshByCmdbId('node', config.host_id)
    oshs.append(node_osh)

    instance = db.DatabaseServer(ip, port)
    inst_osh, _, _, vector = reporter.reportServerAndDatabases(
        instance, node_osh)
    oshs.extend(vector)

    alias_osh = reporter.reportDbAlias(dbname, inst_osh)
    db2_topology.Builder.update_credential_id(alias_osh, cred_id)
    oshs.append(alias_osh)

    if db_oshs:
        db_osh = db_oshs.pop()
        realization_osh = link_reporter.report_realization(alias_osh, db_osh)
        oshs.append(realization_osh)

    return oshs, warnings
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    try:
        client = Framework.createClient()
        vendor = Framework.getDestinationAttribute("discovered_vendor")
        hostId = Framework.getDestinationAttribute("hostId")
        host_osh = modeling.createOshByCmdbId("firewall", hostId)
        discoverer = firewall_discoverer.getDiscoverer(vendor, client)
        if not discoverer:
            raise ValueError("Unsupported device.")
        firewall_config = discoverer.discover()
        OSHVResult.addAll(firewall.reportTopology(firewall_config, host_osh))
    except:
        import sys

        logger.debugException("")
        error_str = str(sys.exc_info()[1]).strip()
        logger.reportError(error_str)
    finally:
        client and client.close()
    ## Write implementation to return new result CIs here...
    if OSHVResult.size() == 0:
        logger.debug("No data discovered from destination.")
        logger.reportWarning("No data discovered from destination.")
    return OSHVResult
예제 #10
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    shell = None
    protocol = Framework.getDestinationAttribute("Protocol")
    switchId = Framework.getDestinationAttribute("hostId")
    print "Switch id %s" % switchId
    errorMessage = None
    try:
        client = Framework.createClient()
        try:
            shellFactory = shellutils.ShellFactory()
            shell = shellFactory.createShell(client)
            switchOsh = modeling.createOshByCmdbId("switch", switchId)
            discoverer = NexusDiscoverer(Framework, shell, "", "", "", "")
            discoverer.discoverInterfacesAndIps()
            interfaces_dict = discoverer.hostDataObject.interfaces
            ports_map = parsePorts(interfaces_dict.values())
            vlan_discoverer = layer2_shell_discoverer.VlanDiscoverer(shell)
            vlans = vlan_discoverer.discoverVlans()

            layer2_discoverer = layer2_shell_discoverer.Layer2Discoverer(shell)
            remote_peers_map = layer2_discoverer.discover()

            OSHVResult.addAll(layer2.reportTopology(switchOsh, interfaces_dict, vlans, remote_peers_map, ports_map))

        finally:
            try:
                shell and shell.closeClient()
            except:
                logger.debugException("")
                logger.error("Unable to close shell")
    except JException, ex:
        errorMessage = ex.getMessage()
예제 #11
0
def reportProcessToPort(hostId, processes, endpoints):
    if not (processes and endpoints):
        return
    vector = ObjectStateHolderVector()
    hostOsh = modeling.createOshByCmdbId('node', hostId)
    vector.add(hostOsh)
    proc_builder = ProcessBuilder()
    key_to_endpoints_map = {}
    [
        key_to_endpoints_map.update({x.getKey(): x.getEndpoints()})
        for x in endpoints
    ]
    for process in processes:
        processOsh = proc_builder.buildProcessOsh(process)
        processOsh.setContainer(hostOsh)
        vector.add(processOsh)
        remotes = key_to_endpoints_map.get(process.getPid())
        if remotes:
            for remote in remotes:
                if not netutils.isValidIp(remote.getAddress()):
                    logger.debug(remote, ' is not a valid ip')
                    continue
                builder = netutils.ServiceEndpointBuilder()
                reporter = netutils.EndpointReporter(builder)
                nodeOsh = reporter.reportHostFromEndpoint(remote)
                endpointOsh = reporter.reportEndpoint(remote, nodeOsh)
                linkOsh = modeling.createLinkOSH('client_server', processOsh,
                                                 endpointOsh)
                linkOsh.setStringAttribute('clientserver_protocol', 'tcp')
                vector.add(nodeOsh)
                vector.add(endpointOsh)
                vector.add(linkOsh)
    return vector
예제 #12
0
def DiscoveryMain(Framework):
    ip = Framework.getTriggerCIData('ip_address')
    credentialIds = netutils.getAvailableProtocols(Framework, 'ucs', ip)
    if not credentialIds:
        logger.warn('No generic credential for UCS')
        Framework.reportWarning('No generic credential for UCS')
        return

    ucs_id = Framework.getTriggerCIData('ucs_id')

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

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

        logger.warn(
            'All credentials have been tried. No credential can connect to UCS by ip %s'
            % ip)
        Framework.reportWarning(
            'All credentials have been tried. No credential can connect to UCS by ip %s'
            % ip)
예제 #13
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    dbFileId = Framework.getDestinationAttribute('dbFileId')
    dbFilePath = Framework.getDestinationAttribute('dbFilePath')
    fsIds = Framework.getTriggerCIDataAsList('fsId') 
    mountPoints = Framework.getTriggerCIDataAsList('mountPoints')
    logger.debug(mountPoints)
    logger.debug(dbFilePath)
    (index, mountPoint) = getMountPoint(dbFilePath, mountPoints)
    if mountPoint:
        fsOsh = modeling.createOshByCmdbId('file_system', fsIds[index])
        dbDatafileOsh = modeling.createOshByCmdbId('dbdatafile', dbFileId)
        linkOsh = modeling.createLinkOSH('usage', dbDatafileOsh, fsOsh)
        OSHVResult.add(fsOsh)
        OSHVResult.add(dbDatafileOsh)
        OSHVResult.add(linkOsh)
        
    return OSHVResult
def reportWebSeal(host_id, credential_id):
    vector = ObjectStateHolderVector()
    hostOsh = modeling.createOshByCmdbId('node', host_id)
    websealOsh = ObjectStateHolder('isam_web')
    websealOsh.setContainer(hostOsh)
    websealOsh.setStringAttribute('discovered_product_name', 'IBM Security Access Manager')
    websealOsh.setStringAttribute('isam_credentials_id', credential_id)
    vector.add(hostOsh)
    vector.add(websealOsh)
    return vector
예제 #15
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    policy_files = Framework.getTriggerCIDataAsList('POLICY_FILE')
    ohs_context = Framework.getTriggerCIData('OHS_CONTEXT')
    ohs_context_id = Framework.getTriggerCIData('OHS_CONTEXT_ID')
    ohs_id = Framework.getTriggerCIData('OHS_ID')
    ohs_address = Framework.getTriggerCIData('OHS_ADDRESS')

    ohsOsh = modeling.createOshByCmdbId('apache', ohs_id)
    ohsContextOsh = modeling.createOshByCmdbId('httpcontext', ohs_context_id)

    for policy_file in policy_files:
        policy_conent = getunZippedContent(policy_file)
        authorization_policies = parse_oam_policy(policy_conent)
        redirect_policies = get_redirect_policies(authorization_policies)
        matched_policies = find_matched_redirect_policies(ohs_context, redirect_policies)
        addResultsToVector(OSHVResult, ohsOsh, ohsContextOsh, matched_policies, ohs_address)

    return OSHVResult
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()

    protocol = Framework.getDestinationAttribute('Protocol')
    hostCmdbId = Framework.getDestinationAttribute('hostId')
    managedSystemCmdbId = Framework.getDestinationAttribute('managedSystemId')
    osType = Framework.getDestinationAttribute('osType')

    client = None
    shell = None
    hostOsh = modeling.createOshByCmdbId('host', hostCmdbId)
    managedSystemOsh = modeling.createOshByCmdbId('ibm_pseries_frame', managedSystemCmdbId)
    try:
        client = Framework.createClient()
        shell = shellutils.ShellUtils(client)
        OSHVResult = doDiscovery(shell, hostOsh, managedSystemOsh, Framework, osType)
    except Exception, ex:
        exInfo = ex.getMessage()
        errormessages.resolveAndReport(exInfo, protocol, Framework)
def reportWebSeal(host_id, credential_id):
    vector = ObjectStateHolderVector()
    hostOsh = modeling.createOshByCmdbId('node', host_id)
    websealOsh = ObjectStateHolder('isam_web')
    websealOsh.setContainer(hostOsh)
    websealOsh.setStringAttribute('discovered_product_name',
                                  'IBM Security Access Manager')
    websealOsh.setStringAttribute('isam_credentials_id', credential_id)
    vector.add(hostOsh)
    vector.add(websealOsh)
    return vector
예제 #18
0
def reportStackedSwithces(sw_oshs, host_id, host_class):
    host_osh = modeling.createOshByCmdbId(host_class, host_id)
    vector = ObjectStateHolderVector()
    if not sw_oshs:
        return vector
    vector.add(host_osh)
    for sw_osh in sw_oshs:
        link_osh = modeling.createLinkOSH('membership', host_osh, sw_osh)
        vector.add(sw_osh)
        vector.add(link_osh)
    return vector
예제 #19
0
def discoverIvmTopology(shell, hostId, reportHostName):
    vector = ObjectStateHolderVector()
    hypervisor = IvmHypervisorDiscoverer(shell).discover()
    virtual_servers = VirtualServerDiscoverer(shell).discover()
    
    ivmHostOsh = modeling.createOshByCmdbId("host_node", hostId)
    vector.add(ivmHostOsh)
    
    vector.addAll(TopologyReporter().report(ivmHostOsh, hypervisor, virtual_servers, reportHostName))
    
    return vector
예제 #20
0
def discoverIvmTopology(shell, hostId, reportHostName):
    vector = ObjectStateHolderVector()
    hypervisor = IvmHypervisorDiscoverer(shell).discover()
    virtual_servers = VirtualServerDiscoverer(shell).discover()

    ivmHostOsh = modeling.createOshByCmdbId("host_node", hostId)
    vector.add(ivmHostOsh)

    vector.addAll(TopologyReporter().report(ivmHostOsh, hypervisor,
                                            virtual_servers, reportHostName))

    return vector
예제 #21
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    policy_files = Framework.getTriggerCIDataAsList('POLICY_FILE')
    ohs_context = Framework.getTriggerCIData('OHS_CONTEXT')
    ohs_context_id = Framework.getTriggerCIData('OHS_CONTEXT_ID')
    ohs_id = Framework.getTriggerCIData('OHS_ID')
    ohs_address = Framework.getTriggerCIData('OHS_ADDRESS')

    ohsOsh = modeling.createOshByCmdbId('apache', ohs_id)
    ohsContextOsh = modeling.createOshByCmdbId('httpcontext', ohs_context_id)

    for policy_file in policy_files:
        policy_conent = getunZippedContent(policy_file)
        authorization_policies = parse_oam_policy(policy_conent)
        redirect_policies = get_redirect_policies(authorization_policies)
        matched_policies = find_matched_redirect_policies(
            ohs_context, redirect_policies)
        addResultsToVector(OSHVResult, ohsOsh, ohsContextOsh, matched_policies,
                           ohs_address)

    return OSHVResult
예제 #22
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()

    protocol = Framework.getDestinationAttribute('Protocol')
    hostCmdbId = Framework.getDestinationAttribute('hostId')
    managedSystemCmdbId = Framework.getDestinationAttribute('managedSystemId')
    osType = Framework.getDestinationAttribute('osType')

    client = None
    shell = None
    hostOsh = modeling.createOshByCmdbId('host', hostCmdbId)
    managedSystemOsh = modeling.createOshByCmdbId('ibm_pseries_frame',
                                                  managedSystemCmdbId)
    try:
        client = Framework.createClient()
        shell = shellutils.ShellUtils(client)
        OSHVResult = doDiscovery(shell, hostOsh, managedSystemOsh, Framework,
                                 osType)
    except Exception, ex:
        exInfo = ex.getMessage()
        errormessages.resolveAndReport(exInfo, protocol, Framework)
예제 #23
0
def DiscoveryMain(Framework):
    ip = Framework.getTriggerCIData('ip_address')
    credentialIds = netutils.getAvailableProtocols(Framework, 'ucs', ip)
    if not credentialIds:
        logger.warn('No generic credential for UCS')
        Framework.reportWarning('No generic credential for UCS')
        return

    ucs_id = Framework.getTriggerCIData('ucs_id')

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

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

        logger.warn('All credentials have been tried. No credential can connect to UCS by ip %s' % ip)
        Framework.reportWarning('All credentials have been tried. No credential can connect to UCS by ip %s' % ip)
예제 #24
0
def triggered_on_alias(client, framework, dns_resolver, cred_id, ip, dbname, port, alias_id):
    db_oshs, oshs, warnings = _discover(client, framework, dns_resolver, cred_id, dbname, port)

    if db_oshs:
        db_osh = db_oshs.pop()
        reporter = db2_topology.LinkReporter()

        alias_osh = modeling.createOshByCmdbId('db2_alias', alias_id)
        db2_topology.Builder.update_credential_id(alias_osh, cred_id)
        oshs.append(alias_osh)

        realization_osh = reporter.report_realization(alias_osh, db_osh)
        oshs.append(realization_osh)

    return oshs, warnings
예제 #25
0
def createIpsNetworksOSHV(ipList, sysTable, hostId, hostIsComplete):
    ipsAndNetworksOSHV = ObjectStateHolderVector()
    isRoute = checkIsRoute(ipList)
    hostOSH = modeling.createOshByCmdbId(sysTable.sysClass, hostId)
    builder = HostBuilder(hostOSH)
    
    builder.setAsRouter(isRoute, __NOT_SET_ROLE)    
    if str(sysTable.sysModel).lower() != 'unknown':
        builder.setStringAttribute("host_model", sysTable.sysModel)
    if str(sysTable.sysOs).lower() != 'unknown':
        builder.setOsName(sysTable.sysOs)
    if str(sysTable.sysVendor).lower() != 'unknown':
        builder.setStringAttribute("host_vendor", sysTable.sysVendor)
    if sysTable.sysName != None and str(sysTable.sysName).lower() != 'unknown':
        builder.setStringAttribute("host_snmpsysname", sysTable.sysName)
    if sysTable.sysNodeName is not None:
        builder.setStringAttribute("host_hostname", sysTable.sysNodeName)
    hostOSH = builder.build()
    ipsAndNetworksOSHV.add(hostOSH)
    
    for ip in ipList:
        if not isValidIP(ip):
            continue
        #create ip object
        ipOSH = modeling.createIpOSH(ip.ipAddr, ip.ipNetMask)
        
        #create network object
        networkOSH = modeling.createNetworkOSH(ip.ipAddr, ip.ipNetMask)
        if ip.nettype != None and int(ip.nettype) > 0:
            networkOSH.setEnumAttribute("network_nettype", int(ip.nettype))
        
        #create member link object ( end1(network) and end2(ip) )
        memberLinkOSHIpNetwork = modeling.createLinkOSH("member", networkOSH, ipOSH)
        
        #create member link object ( end1(network) and end2(host) )
        memberLinkOSHHostNetwork = modeling.createLinkOSH("member", networkOSH, hostOSH)
        
        #create contained link object ( end1(host) and end2(ip) )
        if Boolean.parseBoolean(hostIsComplete):
            containedLinkOSHIpHost = modeling.createLinkOSH("contained", hostOSH, ipOSH)
            ipsAndNetworksOSHV.add(containedLinkOSHIpHost)
        
        ipsAndNetworksOSHV.add(ipOSH)
        ipsAndNetworksOSHV.add(networkOSH)
        ipsAndNetworksOSHV.add(memberLinkOSHIpNetwork)
        ipsAndNetworksOSHV.add(memberLinkOSHHostNetwork)
    
    return ipsAndNetworksOSHV
예제 #26
0
def triggered_on_alias(client, framework, dns_resolver, cred_id, ip, dbname,
                       port, alias_id):
    db_oshs, oshs, warnings = _discover(client, framework, dns_resolver,
                                        cred_id, dbname, port)

    if db_oshs:
        db_osh = db_oshs.pop()
        reporter = db2_topology.LinkReporter()

        alias_osh = modeling.createOshByCmdbId('db2_alias', alias_id)
        db2_topology.Builder.update_credential_id(alias_osh, cred_id)
        oshs.append(alias_osh)

        realization_osh = reporter.report_realization(alias_osh, db_osh)
        oshs.append(realization_osh)

    return oshs, warnings
예제 #27
0
def createBridgeObjects(bridgeList, hostId):
    bridgeObjects = ObjectStateHolderVector()
    
    for bridge in bridgeList:
        #Create bridge with host (To set the bridge container attribute)
        discoveredHostOSH = modeling.createOshByCmdbId("host", hostId)
        #create bridge object
        bridgeOSH = ObjectStateHolder("bridge")
        bridgeMacStr = str(bridge.baseBridgeMacAddress)
        if bridgeMacStr != None:
            bridgeOSH.setStringAttribute("bridge_basemacaddr", bridgeMacStr.upper())
        else: 
            bridgeOSH.setStringAttribute("bridge_basemacaddr", bridgeMacStr)
        #Set the bridge container
        bridgeOSH.setContainer(discoveredHostOSH)
        bridgeObjects.add(bridgeOSH)
    
    return bridgeObjects
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()

    ip = Framework.getDestinationAttribute("ip_address")
    ip_domain = Framework.getDestinationAttribute("ip_domain")
    cmdb_id = Framework.getDestinationAttribute("cmdb_id")
    protocolName = ClientsConsts.HTTP_PROTOCOL_NAME
    connectionFailedMsgs = []
    protocolIds = findProperProtocolIds(
        ip, netutils.getAvailableProtocols(Framework, protocolName, ip, ip_domain) or []
    )

    if not protocolIds:
        msg = errormessages.makeErrorMessage(protocolName, pattern=errormessages.ERROR_NO_CREDENTIALS)
        errobj = errorobject.createError(errorcodes.NO_CREDENTIALS_FOR_TRIGGERED_IP, [protocolName], msg)
        logger.reportErrorObject(errobj)
    else:
        for protocolId in protocolIds:
            protocol = ProtocolManager.getProtocolById(protocolId)
            port = protocol.getProtocolAttribute("protocol_port")

            for version in SUPPORTED_OAM_VERSION:
                props = Properties()
                props.setProperty(CollectorsConstants.ATTR_CREDENTIALS_ID, protocolId)
                props.setProperty("autoAcceptCerts", "true")
                props.setProperty("host", ip)
                try:
                    httpClient = Framework.createClient(props)
                    httpClient.getAsString(
                        "http://%s:%s/oam/services/rest/%s/ssa/policyadmin/appdomain" % (ip, port, version)
                    )

                    oamOsh = modeling.createOshByCmdbId("running_software", cmdb_id)
                    oamOsh.setStringAttribute("credentials_id", protocolId)
                    oamOsh.setStringAttribute("version", version)
                    OSHVResult.add(oamOsh)
                except SocketTimeoutException, e:
                    msg = errormessages.makeErrorMessage(protocolName, pattern=errormessages.ERROR_TIMEOUT)
                    connectionFailedMsgs.append(msg)
                except JException, e:
                    msg = "URL is not accessable: " + e.getMessage()
                    # logger.debugException(msg)
                    connectionFailedMsgs.append(msg)
                finally:
예제 #29
0
def DiscoveryMain(Framework):

    logger.info('Starting HACMP Topology')
    OSHVResult = ObjectStateHolderVector()

    # Get Destination Attribute Section

    hostIP = Framework.getDestinationAttribute('ip_address')
    hostOS = Framework.getDestinationAttribute('host_os')
    hostOS = hostOS or 'NA'
    hostCmdbId = Framework.getDestinationAttribute('hostId')

    physicalHostOsh = modeling.createOshByCmdbId('host', hostCmdbId)
    #  Get Parameter Section

    AIX_ClusterPackageName = Framework.getParameter(
        'AIX_ClusterPackageName') or 'cluster.license'
    cldisp_command = Framework.getParameter('cldisp_command') or 'cldisp'

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

        # We got a good client connection , determine if HACMP is installed
        # If we find HACMP then build a Cluster and Clustered Servers (Nodes) with storage and interfaces

        version = getClusterVersion(shell, hostOS, AIX_ClusterPackageName)
        if version is None:
            logger.warnException('')
            Framework.reportWarning("No HACMP package found")
        else:
            logger.info(concatenate('HACMP package version: ', version))
            hostOSH = createHostOSH(hostIP)
            OSHVResult.addAll(
                CreateCluster(shell, version, hostOSH, hostIP, cldisp_command,
                              Framework))
            OSHVResult.addAll(createstorage(shell, physicalHostOsh))
            OSHVResult.addAll(
                createinterfaces(shell, physicalHostOsh, Framework))
            client.close()
    except JavaException, ex:
        strException = ex.getMessage()
        logger.debugException('')
        Framework.reportError("Protocol Failure, Unable to connect to client")
예제 #30
0
def DiscoveryMain(Framework):

    logger.info('Starting HACMP Topology')
    OSHVResult = ObjectStateHolderVector()


    # Get Destination Attribute Section
    
    hostIP = Framework.getDestinationAttribute('ip_address')
    hostOS = Framework.getDestinationAttribute('host_os')
    hostOS = hostOS or 'NA'
    hostCmdbId = Framework.getDestinationAttribute('hostId')
            
    physicalHostOsh = modeling.createOshByCmdbId('host', hostCmdbId)
    #  Get Parameter Section
    
        
    AIX_ClusterPackageName = Framework.getParameter('AIX_ClusterPackageName') or 'cluster.license' 
    cldisp_command = Framework.getParameter('cldisp_command') or 'cldisp'
 
    try:
        client = Framework.createClient()
        shell = ShellUtils(client)

            # We got a good client connection , determine if HACMP is installed 
            # If we find HACMP then build a Cluster and Clustered Servers (Nodes) with storage and interfaces
            
        version = getClusterVersion(shell, hostOS, AIX_ClusterPackageName)
        if version is None:
            logger.warnException('')
            Framework.reportWarning("No HACMP package found")
        else:
            logger.info(concatenate('HACMP package version: ', version))
            hostOSH = createHostOSH(hostIP)                 
            OSHVResult.addAll(CreateCluster(shell, version, hostOSH,   hostIP,  cldisp_command,  Framework))
            OSHVResult.addAll(createstorage(shell, physicalHostOsh))
            OSHVResult.addAll(createinterfaces(shell, physicalHostOsh, Framework))
            client.close()
    except JavaException, ex:
        strException = ex.getMessage()
        logger.debugException('')
        Framework.reportError("Protocol Failure, Unable to connect to client")
예제 #31
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()

    ip = Framework.getDestinationAttribute('ip_address')
    ip_domain = Framework.getDestinationAttribute('ip_domain')
    cmdb_id = Framework.getDestinationAttribute('cmdb_id')
    protocolName = ClientsConsts.HTTP_PROTOCOL_NAME
    connectionFailedMsgs = []
    protocolIds = findProperProtocolIds(ip, netutils.getAvailableProtocols(Framework, protocolName, ip, ip_domain) or [])

    if not protocolIds:
        msg = errormessages.makeErrorMessage(protocolName, pattern=errormessages.ERROR_NO_CREDENTIALS)
        errobj = errorobject.createError(errorcodes.NO_CREDENTIALS_FOR_TRIGGERED_IP, [protocolName], msg)
        logger.reportErrorObject(errobj)
    else:
        for protocolId in protocolIds:
            protocol = ProtocolManager.getProtocolById(protocolId)
            port = protocol.getProtocolAttribute('protocol_port')

            for version in SUPPORTED_OAM_VERSION:
                props = Properties()
                props.setProperty(CollectorsConstants.ATTR_CREDENTIALS_ID, protocolId)
                props.setProperty('autoAcceptCerts', 'true')
                props.setProperty('host', ip)
                try:
                    httpClient = Framework.createClient(props)
                    httpClient.getAsString('http://%s:%s/oam/services/rest/%s/ssa/policyadmin/appdomain' % (ip, port, version))

                    oamOsh = modeling.createOshByCmdbId('running_software', cmdb_id)
                    oamOsh.setStringAttribute('credentials_id', protocolId)
                    oamOsh.setStringAttribute('version', version)
                    OSHVResult.add(oamOsh)
                except SocketTimeoutException, e:
                    msg = errormessages.makeErrorMessage(protocolName, pattern=errormessages.ERROR_TIMEOUT)
                    connectionFailedMsgs.append(msg)
                except JException, e:
                    msg = 'URL is not accessable: ' + e.getMessage()
                    # logger.debugException(msg)
                    connectionFailedMsgs.append(msg)
                finally:
예제 #32
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    protocol = Framework.getDestinationAttribute('Protocol')
    hostId = Framework.getDestinationAttribute('hostId')
    virshPath = Framework.getParameter('virsh_path')
    prepareVirshPathList(virshPath)
    try:
        shell = None
        try:
            client = Framework.createClient()
            shell = shellutils.ShellUtils(client)
            rootServerOsh = modeling.createOshByCmdbId('host_node', hostId)
            OSHVResult.addAll(doDicovery(shell, Framework, rootServerOsh))
        finally:
            try:
                shell and shell.closeClient()
            except:
                logger.debugException("")
                logger.error("Unable to close shell")
    except JavaException, ex:
        strException = ex.getMessage()
        errormessages.resolveAndReport(strException, protocol, Framework)
예제 #33
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    protocol = Framework.getDestinationAttribute('Protocol')
    hostId = Framework.getDestinationAttribute('hostId')
    virshPath = Framework.getParameter('virsh_path')
    prepareVirshPathList(virshPath)
    try:
        shell = None
        try:
            client = Framework.createClient()
            shell = shellutils.ShellUtils(client)
            rootServerOsh = modeling.createOshByCmdbId('host_node', hostId)
            OSHVResult.addAll(doDicovery(shell, Framework, rootServerOsh))
        finally:
            try:
                shell and shell.closeClient()
            except:
                logger.debugException("")
                logger.error("Unable to close shell")
    except JavaException, ex:
        strException = ex.getMessage()
        errormessages.resolveAndReport(strException, protocol, Framework)
예제 #34
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    protocol = Framework.getDestinationAttribute('Protocol')
    ipList = Framework.getTriggerCIDataAsList('ip_address')
    hostId = Framework.getDestinationAttribute('id')
    hostOSH = modeling.createOshByCmdbId('host', hostId)

    clientShUtils = None
    errorsList = []
    warningsList = []

    #the job triggered on windows with more than one IP, so at least two IP available
    #so we can connect to cluster IP and communicate with some other machine
    #in that case we have to check is connected IP a cluster IP and reconnect by dedicated one
    for ip in ipList:
        try:
            props = Properties()
            props.setProperty(CollectorsConstants.DESTINATION_DATA_IP_ADDRESS,
                              ip)
            client = Framework.createClient(props)
            clientShUtils = shellutils.ShellUtils(client)
            discoveryNLB(clientShUtils, OSHVResult, hostOSH, Framework, ip)
            errorsList = []
            warningsList = []
            break
        except ConnectedToClusterIpException:
            try:
                clientShUtils and clientShUtils.closeClient()
            except:
                logger.debugException("")
                logger.error('Unable to close shell')
            clientShUtils = None
        except NoNlbControlUtilityException, ex:
            logger.reportWarning('No NLB control utility found')
            break
        except JavaException, ex:
            strException = ex.getMessage()
            errormessages.resolveAndAddToObjectsCollections(
                strException, protocol, warningsList, errorsList)
예제 #35
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    protocol = Framework.getDestinationAttribute('Protocol')
    ipList = Framework.getTriggerCIDataAsList('ip_address')
    hostId = Framework.getDestinationAttribute('id')
    hostOSH = modeling.createOshByCmdbId('host', hostId)

    clientShUtils = None
    errorsList = []
    warningsList= []

    #the job triggered on windows with more than one IP, so at least two IP available
    #so we can connect to cluster IP and communicate with some other machine
    #in that case we have to check is connected IP a cluster IP and reconnect by dedicated one
    for ip in ipList:
        try:
            props = Properties()
            props.setProperty(CollectorsConstants.DESTINATION_DATA_IP_ADDRESS, ip)
            client = Framework.createClient(props)
            clientShUtils = shellutils.ShellUtils(client)
            discoveryNLB(clientShUtils, OSHVResult, hostOSH, Framework, ip)
            errorsList = []
            warningsList= []
            break
        except ConnectedToClusterIpException:
            try:
                clientShUtils and clientShUtils.closeClient()
            except:
                logger.debugException("")
                logger.error('Unable to close shell')
            clientShUtils = None
        except NoNlbControlUtilityException, ex:
            logger.reportWarning('No NLB control utility found')
            break
        except JavaException, ex:
            strException = ex.getMessage()
            errormessages.resolveAndAddToObjectsCollections(strException, protocol, warningsList, errorsList)
예제 #36
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    try:
        client = Framework.createClient()
        vendor = Framework.getDestinationAttribute('discovered_vendor')
        hostId = Framework.getDestinationAttribute('hostId')
        host_osh = modeling.createOshByCmdbId('firewall', hostId)
        discoverer = firewall_discoverer.getDiscoverer(vendor, client)
        if not discoverer:
            raise ValueError('Unsupported device.')
        firewall_config = discoverer.discover()
        OSHVResult.addAll(firewall.reportTopology(firewall_config, host_osh))
    except:
        import sys
        logger.debugException('')
        error_str = str(sys.exc_info()[1]).strip()
        logger.reportError(error_str)
    finally:
        client and client.close()
    ## Write implementation to return new result CIs here...
    if OSHVResult.size() == 0:
        logger.debug('No data discovered from destination.')
        logger.reportWarning('No data discovered from destination.')
    return OSHVResult
예제 #37
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    try:
        client = Framework.createClient()
        shell = shellutils.ShellFactory().createShell(client)
        reportHostName = Framework.getParameter('reportLparNameAsHostName')

        if not reportHostName:
            reportHostName = 'false'

        fsm_id = Framework.getDestinationAttribute('fsmId')
        fsm_osh = modeling.createOshByCmdbId('ibm_fsm', fsm_id)

        #do dsscovery part
        supported_types = ibm_fsm_discoverer.getAvailableSupportedEntityTypes(
            shell)
        logger.debug(
            'Found following supported types %s. Will proceed to discovery' %
            supported_types)

        chassis_discoverer = ibm_fsm_discoverer.ChassisDiscoverer(shell)
        chassis = chassis_discoverer.discover()
        #logger.debug('Discovered chassis %s' % chassis)

        farm_discoverer = ibm_fsm_discoverer.FarmDiscoverer(shell)
        farms = farm_discoverer.discover()

        server_discoverer = ibm_fsm_discoverer.ServerDiscoverer(shell)
        servers, vms = server_discoverer.discover()
        #logger.debug('Discovered servers %s' % servers)
        #logger.debug('Discovered vms %s' % vms)

        system_pool_discoverer = ibm_fsm_discoverer.SystemPoolDiscoverer(shell)
        system_pools = system_pool_discoverer.discover()

        switch_discoverer = ibm_fsm_discoverer.SwitchDiscoverer(shell)
        switches = switch_discoverer.discover()

        storage_discoverer = ibm_fsm_discoverer.StorageDiscoverer(shell)
        storages = storage_discoverer.discover()
        #logger.debug('Discovered storage systems %s ' % storages)

        managed_system_details_discoverer = ibm_fsm_discoverer.ManagedSystemDiscoverer(
            shell, servers)
        servers = managed_system_details_discoverer.discover()

        #lpar_details_discoverer = ibm_fsm_discoverer.LParDiscoverer(shell)
        #for server in servers:
        #    server.lpars_dict = lpar_details_discoverer.discover(server.managedSystem)

        for server in servers:
            if not server.managedSystem:
                logger.debug(
                    'Skipping %s, since it is not fully discoverable.' %
                    server)
                continue
            managedSystemName = server.managedSystem.genericParameters.name
            '''Command will fail on the target device if its state is 'Incomplete', skip them'''
            if server.managedSystem.genericParameters.state == 'Incomplete':
                continue

            server.managedSystem.lparProfilesDict = ibm_fsm_discoverer.LParDiscoverer(
                shell).discover(server.managedSystem)
            server.managedSystem.cpuPoolList = ibm_fsm_discoverer.ProcessorPoolDiscoverer(
                shell).discover(managedSystemName)
            server.managedSystem.vScsiList = ibm_fsm_discoverer.ScsiDiscoverer(
                shell).discover(managedSystemName)
            server.managedSystem.vEthList = ibm_fsm_discoverer.EthernetDiscoverer(
                shell).discover(managedSystemName)
        ibm_fsm_discoverer.discoverIoSlots(shell, servers)
        ibm_fsm_discoverer.discoverVirtIoSlots(shell, servers)

        #do topology reporting
        OSHVResult = ibm_fsm.ReportTopology(chassis, servers, system_pools,
                                            vms, switches, storages, fsm_osh,
                                            reportHostName)
    except:
        logger.debugException('')
        logger.reportError('Failed to discover FSM see logs for details')
    return OSHVResult
예제 #38
0
def processObjects(allObjects):
    vector = ObjectStateHolderVector()
    iter = allObjects.iterator()
  
    ciList = []
    ciDict = {}
    createCi = 1
    while iter.hasNext():
        attributes = []
        objectElement = iter.next()
        mamId = objectElement.getAttribute('mamId').getValue()
        cit = objectElement.getAttribute('name').getValue()
        if mamId != None and cit != None:
            allAttributes = objectElement.getChildren('field')
            iterAtt = allAttributes.iterator()    
            attid = ""
            while iterAtt.hasNext():
                attElement = iterAtt.next()
                attName = attElement.getAttribute('name').getValue()
                attType = attElement.getAttribute('datatype').getValue()
                attKey = attElement.getAttribute('key')
                attValue = attElement.getText()
                if cit in host_types and attName == 'id':
                    attid = attValue
                    attName = ""
                    if attid == "":
                        logger.info ('Cannot create host, no UCMDB ID supplied' )
                if cit == 'person' and attName == 'identification_type':
                             attType = 'Enum'
                if attType == None or attType == "":
                    attType = "string"
                if attKey == None or attKey == "":
                    attKey = "false"
                else:
                    attKey = attKey.getValue()
                if attName != "" and attType != "": 
                    attributes.append([attName, attType, attKey, attValue])
                if attKey == "true":
                    if attValue != None and attValue != "":
                        createCi = 1
                    else:
                        createCi = 0
            if createCi == 1:
                ciList.append([mamId, cit, attributes, attid])
                ciDict[mamId] = [mamId, cit, attributes,attid] 
#                
# Process all the attibutes setting them into the OSH 
#
    for ciVal in ciList:
        id = ciVal[0]
        type = ciVal[1]
        if type in host_types:
            osh  =  modeling.createOshByCmdbId(type, ciVal[3])
        else:    
            osh = ObjectStateHolder(type)
        if ciVal[2] != None:
            props = ciVal[2]
            createContainer = 0
            containerOsh = None
            for prop in props:
                if prop[0] == 'root_container':
                    parent = ciDict[prop[3]]
                    if parent != None:
                        parentId = parent[0]
                        parentType = parent[1]
                        parentProps = parent[2]
                        containerOsh = ObjectStateHolder(parentType)
                        if parentProps != None:
                            for parentProp in parentProps:
                                containerOsh.setAttribute(parentProp[0], parentProp[3])
                        createContainer = 1
                if prop[1] == 'Integer':
                    osh.setIntegerAttribute(prop[0], prop[3]) 
                elif prop[1] == 'Long': 
                    osh.setLongAttribute(prop[0], prop[3])
                elif prop[1] == 'Enum':
                    osh.setEnumAttribute(prop[0], int(prop[3]))
                else:
                    osh.setAttribute(prop[0], prop[3]) 
                if createContainer == 1:
                    osh.setContainer(containerOsh)
        vector.add(osh)
    return (vector, ciDict)
예제 #39
0
파일: Util.py 프로젝트: deezeesms/dd-git
def getSqlServer(name,host,sqlserverid):
    return modeling.createOshByCmdbId("sqlserver", sqlserverid)
예제 #40
0
def createRouteObjects(routeList, ifList, ip_address, host_id):
    routeArrayList = []
    routeObjects = ObjectStateHolderVector()
    
    for route in routeList:
        if route.ipRouteType and int(route.ipRouteType) != 4:
            continue
        if str(route.ipRouteNextHop).startswith('0.') or str(route.ipRouteNextHop).startswith('127.'):
            continue  
        if route.ipRouteIfIndex == 0:
            #Host (next hop)
            nextHopHostOSH = __createRouterIncompleteHostByIp(route.ipRouteNextHop)
            #Ip (next hop)
            nextHopIpOSH = modeling.createIpOSH(route.ipRouteNextHop)
            routeObjects.add(nextHopHostOSH)
            routeObjects.add(nextHopIpOSH)
            
        currIf = getInterfaceByIndex(ifList, route.ipRouteIfIndex)
            
        if not currIf:
            continue
        if len(currIf.ipList) == 0 or currIf.ipList[0].netaddr == None:
            #Host (next hop)
            nextHopHostOSH = __createRouterIncompleteHostByIp(route.ipRouteNextHop)
            #Ip (next hop)
            nextHopIpOSH = modeling.createIpOSH(route.ipRouteNextHop)
            discoveredHostOSH = modeling.createOshByCmdbId("host", host_id)
                
            unnumberedLinkOSHHostHost = modeling.createLinkOSH("unnumbered", discoveredHostOSH, nextHopHostOSH)
            #Add the next hop and the link
            routeObjects.add(nextHopHostOSH)
            routeObjects.add(nextHopIpOSH)
            routeObjects.add(unnumberedLinkOSHHostHost)
        else:
            for ip in currIf.ipList:
                nextHopNetAddress = IPv4(route.ipRouteNextHop, ip.ipNetMask).getFirstIp().toString()
                if nextHopNetAddress != ip.netaddr:
                    continue
                    
                nextHopIpDomain =  DomainScopeManager.getDomainByIp(route.ipRouteNextHop, ip.domain)
                routeFound = 0
                for currRoute in routeArrayList:
                    if currRoute['localIpAddress'] == ip.ipAddr and currRoute['localIpDomain'] == ip.domain and currRoute['nextHopIp'] == route.ipRouteNextHop and currRoute['nextHopIpDomain'] == nextHopIpDomain:
                        currRoute['destinationList'].append(route.ipRouteDest)
                        break
                    routeFound += 1
                if routeFound >= len(routeArrayList):
                    currRoute = {}
                    currRoute['destAddress'] = route.ipRouteDest
                    currRoute['destinationList'] = []
                    currRoute['destinationList'].append(route.ipRouteDest)
                    currRoute['ifIndex'] = route.ipRouteIfIndex
                    currRoute['localIpAddress'] = ip.ipAddr
                    currRoute['localIpDomain'] = ip.domain
                    currRoute['localIpMask'] = ip.ipNetMask
                    currRoute['localIpNetClass'] = ip.netclass
                    currRoute['nextHopNetAddr'] = nextHopNetAddress
                    currRoute['nextHopIp'] = route.ipRouteNextHop
                    currRoute['nextHopIpDomain'] = DomainScopeManager.getDomainByIp(currRoute['nextHopIp'], currRoute['localIpDomain'])
                    currRoute['type'] = route.ipRouteType
                    currRoute['ifAdminStatus'] = currIf.ifAdminStatus
                    routeArrayList.append(currRoute)
                        
    for currRouteData in routeArrayList:
        #Ip (next hop)
        nextHopIpOSH = modeling.createIpOSH(currRouteData['nextHopIp'], currRouteData['localIpMask'])
            
        routeObjects.add(nextHopIpOSH)
        # Ip (local for link)
        localIpOSHForLink = modeling.createIpOSH(currRouteData['localIpAddress'])
            
        routeLinkOSHIpIp = modeling.createLinkOSH('route', localIpOSHForLink, nextHopIpOSH) 
            
        for ipDest in currRouteData['destinationList']:
            routeLinkOSHIpIp.addAttributeToList(AttributeStateHolder("route_netaddress", ipDest))
            
        # Network (for link)
        nextHopNetworkOSH = modeling.createNetworkOSH(currRouteData['nextHopNetAddr'], currRouteData['localIpMask'])
            
        nextHopHostOSH = __createRouterIncompleteHostByIp(currRouteData['nextHopIp'])
        #Member (Connecting the next hop host to the next hop network)
        memberLinkOSHHostNetwork = modeling.createLinkOSH('member', nextHopNetworkOSH, nextHopHostOSH)
        #Member (Connecting the next hop ip to the next hop network)
        memberLinkOSHIpNetwork = modeling.createLinkOSH('member', nextHopNetworkOSH, nextHopIpOSH)
            
        routeObjects.add(nextHopHostOSH)
        routeObjects.add(memberLinkOSHHostNetwork)
        routeObjects.add(memberLinkOSHIpNetwork)
        routeObjects.add(routeLinkOSHIpIp)
    
    return routeObjects
예제 #41
0
def createInterfaceObjects(ifList, host_id, ucmdbversion = None):
    result = ObjectStateHolderVector()
    
    discoveredHostOSH = modeling.createOshByCmdbId('host', host_id)
    
    for interface in ifList:
        if interface.ifType and int(interface.ifType) == 24:
            continue
        
        if not modeling.isValidInterface(interface.ifMac, interface.ifDescr, interface.ifName):
            continue
        
        interface.ifDescr = _stripVirtualMiniportInfo(interface.ifDescr)
        
        interfaceOSH = modeling.createInterfaceOSH(interface.ifMac, discoveredHostOSH, interface.ifDescr, interface.ifIndex, interface.ifType, interface.ifAdminStatus, interface.ifOperStatus, interface.ifSpeed, interface.ifName, interface.ifAlias)
        if not interfaceOSH:
            continue

        result.add(interfaceOSH)
        if ucmdbversion and ucmdbversion < 9:
            interfaceIndexOSH = ObjectStateHolder("interfaceindex")
            interfaceIndexOSH.setIntegerAttribute("interfaceindex_index", interface.ifIndex)
            if interface.ifAdminStatus:
                intValue = None
                try:
                    intValue = int(interface.ifAdminStatus)
                except:
                    logger.warn("Failed to convert the interface admin status '%s'" % interface.ifAdminStatus)
                else:
                    if intValue > 0:
                        interfaceIndexOSH.setEnumAttribute("interfaceindex_adminstatus", intValue)
            if interface.ifDescr != None and interface.ifDescr != '':
                interfaceIndexOSH.setStringAttribute("interfaceindex_description", interface.ifDescr)
            if interface.ifIndex != None and interface.ifIndex != '':
                interfaceIndexOSH.setIntegerAttribute("interfaceindex_index", interface.ifIndex)
            if interface.ifSpeed != None and interface.ifSpeed != '':
                interfaceIndexOSH.setDoubleAttribute("interfaceindex_speed", interface.ifSpeed)
            if interface.ifType:
                intValue = None
                try:
                    intValue = int(interface.ifType)
                except:
                    logger.warn("Failed to convert the interface type '%s'" % interface.ifType)
                else:
                    if intValue > 0:
                        interfaceIndexOSH.setEnumAttribute("interfaceindex_type", intValue)
            interfaceIndexOSH.setContainer(discoveredHostOSH)
            result.add(interfaceIndexOSH)
            
    
            parentLinkOSH = modeling.createLinkOSH('parent', interfaceIndexOSH, interfaceOSH)
            result.add(parentLinkOSH)

        for ip in interface.ipList:
            if str(ip.ipAddr).startswith('0.') or str(ip.ipAddr).startswith('127.'):
                continue
            ipOSH = modeling.createIpOSH(ip.ipAddr)
            parentLinkOSH = modeling.createLinkOSH('containment', interfaceOSH, ipOSH)
            result.add(parentLinkOSH)
        
    return result
예제 #42
0
def processObjects(allObjects):
    vector = ObjectStateHolderVector()
    iter = allObjects.iterator()

    ciList = []
    ciDict = {}
    createCi = 1
    while iter.hasNext():
        attributes = []
        objectElement = iter.next()
        mamId = objectElement.getAttribute('mamId').getValue()
        cit = objectElement.getAttribute('name').getValue()
        if mamId != None and cit != None:
            allAttributes = objectElement.getChildren('field')
            iterAtt = allAttributes.iterator()
            attid = ""
            while iterAtt.hasNext():
                attElement = iterAtt.next()
                attName = attElement.getAttribute('name').getValue()
                attType = attElement.getAttribute('datatype').getValue()
                attKey = attElement.getAttribute('key')
                attValue = attElement.getText()
                if cit in host_types and attName == 'id':
                    attid = attValue
                    attName = ""
                    if attid == "":
                        logger.info('Cannot create host, no UCMDB ID supplied')
                if cit == 'person' and attName == 'identification_type':
                    attType = 'Enum'
                if attType == None or attType == "":
                    attType = "string"
                if attKey == None or attKey == "":
                    attKey = "false"
                else:
                    attKey = attKey.getValue()
                if attName != "" and attType != "":
                    attributes.append([attName, attType, attKey, attValue])
                if attKey == "true":
                    if attValue != None and attValue != "":
                        createCi = 1
                    else:
                        createCi = 0
            if createCi == 1:
                ciList.append([mamId, cit, attributes, attid])
                ciDict[mamId] = [mamId, cit, attributes, attid]


#
# Process all the attibutes setting them into the OSH
#
    for ciVal in ciList:
        id = ciVal[0]
        type = ciVal[1]
        if type in host_types:
            osh = modeling.createOshByCmdbId(type, ciVal[3])
        else:
            osh = ObjectStateHolder(type)
        if ciVal[2] != None:
            props = ciVal[2]
            createContainer = 0
            containerOsh = None
            for prop in props:
                if prop[0] == 'root_container':
                    parent = ciDict[prop[3]]
                    if parent != None:
                        parentId = parent[0]
                        parentType = parent[1]
                        parentProps = parent[2]
                        containerOsh = ObjectStateHolder(parentType)
                        if parentProps != None:
                            for parentProp in parentProps:
                                containerOsh.setAttribute(
                                    parentProp[0], parentProp[3])
                        createContainer = 1
                if prop[1] == 'Integer':
                    osh.setIntegerAttribute(prop[0], prop[3])
                elif prop[1] == 'Long':
                    osh.setLongAttribute(prop[0], prop[3])
                elif prop[1] == 'Enum':
                    osh.setEnumAttribute(prop[0], int(prop[3]))
                else:
                    osh.setAttribute(prop[0], prop[3])
                if createContainer == 1:
                    osh.setContainer(containerOsh)
        vector.add(osh)
    return (vector, ciDict)
예제 #43
0
파일: tibco.py 프로젝트: deezeesms/dd-git
 def visitBusinessWorksWithCmdbId(self, bwWithId):
     r'@types: tibco.TopologyBuilder.BusinessWorksWithCmdbId -> ObjectStateHolder'
     assertFunc(bwWithId, ValueError("BusinessWorks with Cmdb Id is None"))
     osh = modeling.createOshByCmdbId(TopologyBuilder.BW_CI_TYPE, bwWithId.cmdbId)
     self.__updateBusinessWorksAttributes(bwWithId.instance, osh)
     return osh
예제 #44
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    try:
        client = Framework.createClient()
        shell = shellutils.ShellFactory().createShell(client)
        reportHostName = Framework.getParameter('reportLparNameAsHostName')
        
        if not reportHostName:
            reportHostName = 'false'
            
        fsm_id = Framework.getDestinationAttribute('fsmId')
        fsm_osh = modeling.createOshByCmdbId('ibm_fsm', fsm_id)
        
        #do dsscovery part
        supported_types = ibm_fsm_discoverer.getAvailableSupportedEntityTypes(shell)
        logger.debug('Found following supported types %s. Will proceed to discovery' % supported_types)
        
        chassis_discoverer = ibm_fsm_discoverer.ChassisDiscoverer(shell)
        chassis = chassis_discoverer.discover()
        #logger.debug('Discovered chassis %s' % chassis)
        
        farm_discoverer = ibm_fsm_discoverer.FarmDiscoverer(shell)
        farms = farm_discoverer.discover()
        
        server_discoverer = ibm_fsm_discoverer.ServerDiscoverer(shell)
        servers, vms = server_discoverer.discover()
        #logger.debug('Discovered servers %s' % servers)
        #logger.debug('Discovered vms %s' % vms)
        
        system_pool_discoverer = ibm_fsm_discoverer.SystemPoolDiscoverer(shell)
        system_pools = system_pool_discoverer.discover()       
   
        switch_discoverer = ibm_fsm_discoverer.SwitchDiscoverer(shell)
        switches = switch_discoverer.discover()
    
        storage_discoverer = ibm_fsm_discoverer.StorageDiscoverer(shell)
        storages = storage_discoverer.discover()
        #logger.debug('Discovered storage systems %s ' % storages)
        
        managed_system_details_discoverer = ibm_fsm_discoverer.ManagedSystemDiscoverer(shell, servers)
        servers = managed_system_details_discoverer.discover()
        
        #lpar_details_discoverer = ibm_fsm_discoverer.LParDiscoverer(shell)
        #for server in servers:
        #    server.lpars_dict = lpar_details_discoverer.discover(server.managedSystem)
        
        for server in servers:
            if not server.managedSystem:
                logger.debug('Skipping %s, since it is not fully discoverable.' % server)
                continue
            managedSystemName = server.managedSystem.genericParameters.name
            
            '''Command will fail on the target device if its state is 'Incomplete', skip them'''
            if server.managedSystem.genericParameters.state == 'Incomplete':
                continue
            
            server.managedSystem.lparProfilesDict = ibm_fsm_discoverer.LParDiscoverer(shell).discover(server.managedSystem)
            server.managedSystem.cpuPoolList = ibm_fsm_discoverer.ProcessorPoolDiscoverer(shell).discover(managedSystemName)
            server.managedSystem.vScsiList = ibm_fsm_discoverer.ScsiDiscoverer(shell).discover(managedSystemName)
            server.managedSystem.vEthList = ibm_fsm_discoverer.EthernetDiscoverer(shell).discover(managedSystemName)
        ibm_fsm_discoverer.discoverIoSlots(shell, servers)
        ibm_fsm_discoverer.discoverVirtIoSlots(shell, servers)

        #do topology reporting
        OSHVResult = ibm_fsm.ReportTopology(chassis, servers, system_pools, vms, switches, storages, fsm_osh, reportHostName)
    except:
        logger.debugException('')
        logger.reportError('Failed to discover FSM see logs for details')
    return OSHVResult
def getSqlServer(name,host,sqlserverid):
    return modeling.createOshByCmdbId("sqlserver", sqlserverid)