Ejemplo n.º 1
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    logger.info('Starting HACMP Applications')
    hostIP = Framework.getDestinationAttribute('ip_address')
    logger.debug ('Host IP: ',hostIP)
    cluster =  Framework.getDestinationAttribute('cluster')
    hostOS = Framework.getDestinationAttribute('host_os')
    hostOS = hostOS or 'NA'
    protocolName = Framework.getDestinationAttribute('Protocol')
    hostId = Framework.getDestinationAttribute('hostId')
    ##  Get Parameter Section
    cldisp_command = Framework.getParameter('cldisp_command') or 'cldisp'
    cllsif_command = Framework.getParameter('cllsif_command') or 'cllsif'

    try:
        client = Framework.createClient()
        shell = ShellUtils(client)
        #   If we get  good client connection , run the client commands to get the Application information for the cluster
        HostOSH = modeling.createOshByCmdbIdString('host', hostId)
        ClusterOSH = getclusterOSH(cluster)
        appDictionary = getapplicationInfo(shell,  cldisp_command,  Framework)
        resourceDictionary = getresourceinfo(shell, cllsif_command)
        OSHVResult.addAll(createserviceapplicationOSH (shell, appDictionary, resourceDictionary, HostOSH, ClusterOSH,   Framework))
        client.close()
    except JavaException, ex:
        strException = ex.getMessage()
        logger.debugException('')
        errormessages.resolveAndReport(strException, protocolName, Framework)
Ejemplo n.º 2
0
def disLinux(hostId, shell, Framework = None, langBund = None):
    ''' Discover physical memory and swap memory on GNU/Linux 
    str, Shell, Framework, Properties -> oshVector
    @command: /usr/bin/free -m
    '''
    myVec = ObjectStateHolderVector()
    hostOsh = modeling.createOshByCmdbIdString('host', hostId)

    output = None
    try:
        output = shell.execCmd('/usr/bin/free -m')#V@@CMD_PERMISION tty protocol execution
        if not output or shell.getLastCmdReturnCode() != 0:
            raise ValueError
    except:
        logger.warn("Failed getting memory size from 'free'")
    else:
        lines = output.split('\n')
        for line in lines:
            if line:
                if re.search('cache', line):
                    continue
                matcher = re.match("Mem:\s+(\d+)\s+", line)
                if matcher:
                    memorySizeInMegabytes = int(matcher.group(1))
                    memorySizeInKilobytes = memorySizeInMegabytes * 1024
                    memory.report(myVec, hostOsh, memorySizeInKilobytes)
                else:
                    matcher = re.match("Swap:\s+(\d+)\s+", line)
                    if matcher:
                        swapMemorySizeInMegabytes = int(matcher.group(1))
                        modeling.setHostSwapMemorySizeAttribute(hostOsh, swapMemorySizeInMegabytes)

    myVec.add(hostOsh)
    return myVec
Ejemplo n.º 3
0
def buildNetDeviceOSHV(localFramework, netDeviceCmdbIdList, netDeviceNameList):
    try:
        returnOSHV = ObjectStateHolderVector()
        ## Check validity of provided lists
        if not netDeviceCmdbIdList:
            localFramework.reportError('Please check adapter parameter <netdevice_cmdbid>')
            return None
        if not netDeviceNameList:
            localFramework.reportError('Please check adapter parameter <netdevice_name>')
            return None
        if len(netDeviceCmdbIdList) != len(netDeviceNameList):
            localFramework.reportError('The lists <netdevice_cmdbid> and <netdevice_name> have different sizes: <%s> and <%s>! Please check adapter input configuration' \
                        % (len(netDeviceCmdbIdList), len(netDeviceNameList)))
            return None

        ## Build OSH and dict
        for netDeviceIndex in range(len(netDeviceCmdbIdList)):
            netDeviceCmdbId = netDeviceCmdbIdList[netDeviceIndex]
            netDeviceName = netDeviceNameList[netDeviceIndex]
            ## Check if attributes are good
            if not netDeviceCmdbId or not netDeviceName:
                logger.debug('Skipping invalid NetDevice name or CMDB ID in adapter input parameter...')
                continue
            ## Build OSH and add to OSHV
            netDeviceOSH = modeling.createOshByCmdbIdString('netdevice', netDeviceCmdbId)
            #netDeviceOSH.setAttribute('name', netDeviceName)
            netDeviceOSH.setAttribute('data_externalid', netDeviceName)
            ciscoworks_utils.debugPrint(4, '[' + SCRIPT_NAME + ':buildNetDeviceOSHV] Built OSH for NetDevice <%s> with CMDB ID <%s>' % (netDeviceName, netDeviceCmdbId))
            returnOSHV.add(netDeviceOSH)
        return returnOSHV
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.warn('[' + SCRIPT_NAME + ':buildNetDeviceOSHV] Exception: <%s>' % excInfo)
        pass
Ejemplo n.º 4
0
def createScpOSHV(container, type, host, port, context, shell, localIP=None, dnsServers=None):
    OSHVResult = ObjectStateHolderVector()
    if not host:
        return OSHVResult
    ipAddresses = []
    if (host in LOCALHOST) and localIP:
        logger.debug("found local ip: %s , use %s instead" % (host, localIP))
        host = localIP
    if netutils.isValidIp(host):
        ipAddresses.append(host)
    else:
        # try to resolve ip address from hostname
        logger.debug('Trying to resolve ip address from hostname:', host)
        ipAddresses = resolveIPByNsLookup(dnsServers, shell, host)
        if len(ipAddresses) == 0:
            ipAddresses = resolveIPByINet(host, port)
        if len(ipAddresses) == 0:
            ipAddresses = resolveIPBySocket(host)

    for ipAddress in ipAddresses:
        if not netutils.isValidIp(ipAddress):
            logger.debug("ignore invalid ip address: ", ipAddress)
            continue
        scpOsh = createScpOsh(container, type, ipAddress, port, context, host)
        OSHVResult.add(scpOsh)
        # Add additional ip CIs for all next hops to make sure new jobs could be triggered.
        ip = ip_addr.IPAddress(ipAddress)
        OSHVResult.add(modeling.createIpOSH(ip))

    return OSHVResult
Ejemplo n.º 5
0
def iterate_over_args(main_fn, framework, cred_args, proto_name, stop_on_first):
    '''
    @param cred_args: parameters you decided to iterate over
    '''
    vector = ObjectStateHolderVector()
    framework = flow.RichFramework(framework)
    creds_manager = flow.CredsManager(framework)
    # as cred_args possibly generator or iterator, realize only first
    first_ = first(cred_args)
    if first_ is None:
        logger.reportErrorObject(flow._create_missed_creds_error(proto_name))
    else:
        # restore cred_args
        cred_args = chain((first_,), cred_args)
        connection_exs = []
        discovery_exs = []
        warnings = []
        at_least_once_discovered = False
        for args in cred_args:
            try:
                oshs, warnings_ = main_fn(framework, creds_manager, *args)
                warnings.extend(warnings_ or ())
                vector.addAll(oshs)
                at_least_once_discovered = True
                if stop_on_first:
                    break
            except flow.ConnectionException, ce:
                logger.debugException(str(ce))
                connection_exs.append(ce)
            except (flow.DiscoveryException, Exception, JException), de:
                logger.debugException(str(de))
                discovery_exs.append(de)
Ejemplo n.º 6
0
def osh_createDdfOsh(db2SubsystemOsh, ddfObj):
    str_name = 'name'
    if UCMDB_VERSION < 9:
        str_name = 'data_name'

    _vector = ObjectStateHolderVector()
    if isNotNull(ddfObj.locationName):
        ddfOsh = ObjectStateHolder('db2_ddf')
        ddfOsh.setAttribute(str_name, ddfObj.locationName)
        ddfOsh.setAttribute('ddf_status', ddfObj.status)
        ddfOsh.setAttribute('ddf_luname', ddfObj.locationLuName)
        ddfOsh.setAttribute('ddf_generic_luname', ddfObj.locationGenericLuName)
        ddfOsh.setAttribute('ddf_ip_address', ddfObj.ipAddress)
        if isNotNull(ddfObj.ipAddress) and isnumeric(ddfObj.ipAddress):
            ddfOsh.setAttribute('ddf_tcp_port', int(ddfObj.tcpPort))
        ddfOsh.setAttribute('ddf_sql_domain', ddfObj.sqlDomain)
        ddfOsh.setContainer(db2SubsystemOsh)
        _vector.add(ddfOsh)
        for alias in ddfObj.ddfAlias:
            ddfAliasOsh = ObjectStateHolder('db2_ddf_alias')
            ddfAliasOsh.setAttribute(str_name, alias.aliasName)
            if isNotNull(alias.aliasPort) and isnumeric(alias.aliasPort):
                ddfAliasOsh.setIntegerAttribute('ddf_alias_port', int(alias.aliasPort))
            ddfAliasOsh.setContainer(ddfOsh)
            _vector.add(ddfAliasOsh)
    return _vector
Ejemplo n.º 7
0
def getPorts(neutronApi, regionName, serverOshDict, networkOshDict):
    vector = ObjectStateHolderVector()
    port_discover = openstack_discoverer.InterfaceDiscoverer(neutronApi, regionName)
    interfaces = port_discover.discover()
    for interface in interfaces:
        vector.addAll(interface.report(serverOshDict, networkOshDict))
    return vector
Ejemplo n.º 8
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()
Ejemplo n.º 9
0
def disFreeBSD(hostObj, client, Framework=None, langBund=None):

    myVec = ObjectStateHolderVector()

    r = client.execCmd("pkg_info -a -I")  # V@@CMD_PERMISION tty protocol execution
    if r == None:
        return myVec

    if re.search("pkg_info: no packages installed", r):
        return myVec

    lines = ""
    if re.search("\r\n", r):
        lines = r.split("\r\n")
    elif re.search("\n", r):
        lines = r.split("\n")
    else:
        return myVec

    for line in lines:
        token = line.split("-", 2)
        if len(token) == 2:
            if token[0]:
                subt = token[1].split()
                myVec.add(hostresource.makeSoftwareOSH2(createHostOSH(hostObj), token[0], "", subt[0]))

    return myVec
Ejemplo n.º 10
0
def makeUserOSH(hostCmdbId, userName, desc, uid, gid, homeDir):
    'host OSH, str, str, str, str, str -> OSH vector'
    iuid = -1
    igid = -1
    try:
        iuid = Long(uid)
    except:
        iuid = -1

    try:
        igid = Long(gid)
    except:
        igid = -1

    myVec = ObjectStateHolderVector()

    u_obj = ObjectStateHolder('osuser')
    host_objSH = modeling.createOshByCmdbIdString('host', hostCmdbId)
    u_obj.setContainer(host_objSH)

    u_obj.setAttribute('data_name', userName)
    if(len(uid) > 0):
        u_obj.setAttribute('user_id', Long(iuid))
    if(len(gid) > 0):
        u_obj.setAttribute('group_id', Long(igid))
    if(len(desc) > 0):
        u_obj.setAttribute('data_note', desc)
    if(len(homeDir) > 0):
        u_obj.setAttribute('homedir', homeDir)
    myVec.add(u_obj)

    return(myVec)
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    ipAddress = Framework.getDestinationAttribute('ip_address')
    credentialsId = Framework.getDestinationAttribute('credentialsId')
    hostId = Framework.getDestinationAttribute('hostId')
    hostOsh = modeling.createOshByCmdbIdString('host', hostId)
    PROTOCOL_NAME = 'PowerShell'
    try:
        client = Framework.createClient()
        shell =shellutils.ShellUtils(client)
        discoverer = None
        try:
            for discovererClass in [msexchange_win_shell.Exchange2007Discoverer, msexchange_win_shell.Exchange2010Discoverer]:
                try:
                    discoverer = discovererClass(shell)
                    exchangeServers = discoverer.discover()
                    for exchangeServer in exchangeServers:
                        topoBuilder = msexchange.TopologyBuilder(exchangeServer, hostOsh, ipAddress, credentialsId)
                        OSHVResult.addAll(topoBuilder.build())
                        break
                except msexchange_win_shell.AddSnapInException:
                    logger.warn('Failed to import Snap-In.')
                    discoverer = None
            if not discoverer:
                raise Exception("Failed to discover MS-Exchange. See Logs for details.")
        finally:
            shell.closeClient()
    except JavaException, ex:
        logger.debugException('')
        strException = str(ex.getMessage())
        errormessages.resolveAndReport(strException, PROTOCOL_NAME, Framework)
Ejemplo n.º 12
0
 def reportSharedResources(self, sharedResource, containerOsh):
     vector = ObjectStateHolderVector()
     pdo = self._builder.SharedResource(sharedResource)
     osh = pdo.build(self._builder)
     osh.setContainer(containerOsh)
     vector.add(osh)
     return vector
Ejemplo n.º 13
0
    def getStoredProcedureFromDB(self, dbName, container, filterInternal):
        result = ObjectStateHolderVector()
        if not self.discoveryOptions.discoverProcedures:
            return result
        # if we working with master table need to ignore MSSQL internal storage procedure
        additionalFilter = ""
        if filterInternal:
            additionalFilter = self.__genAdditionalFilter()

        rs = self.connection.getTable('SELECT ROUTINE_NAME, ROUTINE_TYPE, CREATED, LAST_ALTERED FROM [%s].information_schema.routines WHERE routine_type = \'PROCEDURE\'%s' % (dbName, additionalFilter))
        while rs.next():
            name = rs.getString('ROUTINE_NAME')
            dba_type = rs.getString('ROUTINE_TYPE')
            created = rs.getTimestamp('CREATED')
            last_updated = rs.getTimestamp('LAST_ALTERED')

            if name:
                storedProcedure = ObjectStateHolder('dbaobjects')
                storedProcedure.setContainer(container)
                storedProcedure.setAttribute('name', name)
                storedProcedure.setAttribute('dbaobjects_owner', dbName)
                storedProcedure.setAttribute('dbaobjects_type', dba_type)
                if created:
                    storedProcedure.setDateAttribute('dbaobjects_created', created)
                if last_updated:
                    storedProcedure.setDateAttribute('dbaobjects_lastddltime', last_updated)
                result.add(storedProcedure)
        return result
Ejemplo n.º 14
0
 def decorator(framework):
     vector = ObjectStateHolderVector()
     framework = RichFramework(framework)
     creds_manager = CredsManager(framework)
     creds = creds_manager.get_creds_for_destination(proto_name)
     creds = filter(Fn(is_cred_ok_fn, framework, creds_manager, __), creds)
     if not creds:
         logger.reportErrorObject(_create_missed_creds_error(proto_name))
     else:
         connection_exs = []
         discovery_exs = []
         warnings = []
         at_least_once_discovered = False
         for cred_id in creds:
             try:
                 oshs, warnings = main_fn(framework, creds_manager, cred_id)
                 vector.addAll(oshs)
                 at_least_once_discovered = True
                 if stop_on_first:
                     break
             except ConnectionException, ce:
                 logger.debugException(str(ce))
                 connection_exs.append(ce)
             except (DiscoveryException, Exception, JException), de:
                 logger.debugException(str(de))
                 discovery_exs.append(de)
Ejemplo n.º 15
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    CmdbOIDFactory = CmdbObjectID.Factory
    hostId = CmdbOIDFactory.restoreObjectID(Framework.getDestinationAttribute('hostId'))
    sqlServerId = CmdbOIDFactory.restoreObjectID(Framework.getDestinationAttribute('id'))

    try:
        props = Properties()
 
        instance_name = Framework.getDestinationAttribute('instanceName')
        if instance_name and instance_name != 'NA' and instance_name.find('\\') != -1:
            props.setProperty('sqlprotocol_dbsid', instance_name[instance_name.find('\\')+1:])
        mssqlClient = Framework.createClient(props)
        connection = SqlServerConnection.ClientSqlServerConnection(mssqlClient)
        logger.debug("got connection")
        discoveryOptions = SqlServerDiscoveryOptions()
        discoveryOptions.discoverConfigs = Boolean.parseBoolean(Framework.getParameter('discoverConfigs'))
        discoveryOptions.discoverDbUser = Boolean.parseBoolean(Framework.getParameter('discoverDbUser'))
        discoveryOptions.discoverSqlFile = Boolean.parseBoolean(Framework.getParameter('discoverSqlFile'))
        discoveryOptions.discoverSqlJob = Boolean.parseBoolean(Framework.getParameter('discoverSqlJob'))
        discoveryOptions.discoverProcedures = Boolean.parseBoolean(Framework.getParameter('discoverStoredProcedures'))
        discoveryOptions.discoverInternalProcedures = Boolean.parseBoolean(Framework.getParameter('discoverInternalProcedures'))

        sqlServer = SqlServer.SqlServer(connection, discoveryOptions)
        OSHVResult.addAll(sqlServer.collectData(hostId, sqlServerId, discoveryOptions.discoverConfigs))
        mssqlClient.close()
    except JavaException, ex:
        strException = ex.getMessage()
        errormessages.resolveAndReport(strException, ClientsConsts.SQL_PROTOCOL_NAME, Framework)
Ejemplo n.º 16
0
def createVlanOshv(vlMap, portOshMap):
	vlanHostOshMap = {}
	oshv = ObjectStateHolderVector()
	# process VLANs
	for (vlanId, vlanObj) in vlMap.items():
		ports = vlanObj.ports
		ports.sort()
		for portId in ports:
			if notNull(portOshMap) and portOshMap.has_key(portId):
				vlanOsh = ObjectStateHolder('vlan')
				vlanOsh.setIntegerAttribute('vlan_number', int(vlanObj.vlanId))
				vlanOsh.setAttribute('vlan_aliasname', vlanObj.name)
				vlanOsh.setAttribute('data_name', vlanObj.vlanId)

				if vlanHostOshMap.has_key(vlanObj.vlanId):
					hostOsh = vlanHostOshMap[vlanObj.vlanId]
				else:
					hostOsh = portOshMap[portId].getAttributeValue('root_container')
					oshv.add(vlanOsh)
					vlanHostOshMap[vlanObj.vlanId] = hostOsh
				vlanOsh.setContainer(hostOsh)
				membershipLink = modeling.createLinkOSH("member", portOshMap[portId], vlanOsh)
				oshv.add(membershipLink)

	return oshv
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()    
    ipAddress = Framework.getDestinationAttribute('ip_address')
    credentialsId = Framework.getDestinationAttribute('credentialsId')
    hostId = Framework.getDestinationAttribute('hostId')
    
    hostOsh = ms_exchange_utils.restoreHostById(hostId)

    try:
        shellClient = Framework.createClient()
        client = PowerShellClient(shellClient, Framework)
        try:
            ExchangeServer = client.executeScenario("Exchange_Server_2007_Discovery.ps1")
            
            exchangeServerOsh = modeling.createExchangeServer(hostOsh, ipAddress, credentialsId, ExchangeServer.ExchangeSnapInVersion)
            exchangeServerOsh.setAttribute('guid', normalizeGuid(ExchangeServer.Guid))
            exchangeServerOsh.setAttribute('fqdn', ExchangeServer.Fqdn)
            
            buildNumber = parseBuildNumber(ExchangeServer.AdminDisplayVersion)
            if buildNumber:                
                exchangeServerOsh.setAttribute('build_number', buildNumber)
            #exchangeServerOsh.setAttribute('application_version_number', ExchangeServer.ExchangeSnapInVersion)
            versionNumber = parseExchangeVersion(ExchangeServer.AdminDisplayVersion)
            if versionNumber:
                exchangeServerOsh.setAttribute('application_version_number', exchange_version_mapping[versionNumber])
            exchangeServerOsh.setAttribute('application_version', ExchangeServer.AdminDisplayVersion)
            exchangeServerOsh.setDateAttribute('creation_date', DATE_FORMAT.parse(ExchangeServer.WhenCreated))
            
            OSHVResult.add(exchangeServerOsh)
        finally:
            client.close()
    except Exception, ex:
        logger.debugException('')
        strException = str(ex.getMessage())
        errormessages.resolveAndReport(strException, PROTOCOL_NAME, Framework)
Ejemplo n.º 18
0
def disVMKernel(hostId, shell, Framework = None, langBund = None):
    ''' Discover physical memory on VMKernel 
    str, Shell, Framework, Properties -> oshVector
    @raise ValueError: memory size is not a digit
    @command: esxcfg-info -F xml | sed -n \'/<memory-info>/,/<\/memory-info>/p\'
    '''
    resVec = ObjectStateHolderVector()
    hostOsh = modeling.createOshByCmdbIdString('host', hostId)

    xml = shell.execCmd('esxcfg-info -F xml | sed -n \'/<memory-info>/,/<\/memory-info>/p\' | sed -n \'1,/<\/memory-info>/p\'')
    #Cleanup retrieved xml. Sometimes there is some debug info added
    xml = xml[xml.find('<'): xml.rfind('>') + 1]

    builder = SAXBuilder(0)
    document = builder.build(StringReader(xml))
    rootElement = document.getRootElement()

    memory_values = rootElement.getChild('aux-source-memory-stats').getChildren('value')
    for value in memory_values:
        if value.getAttributeValue('name') == 'physical-memory-est.':
            memorySizeInKilobytes = int(value.getText())
            memory.report(resVec, hostOsh, memorySizeInKilobytes)
    #TODO: Implement swap discovery for vmkernel
    resVec.add(hostOsh)
    return resVec
Ejemplo n.º 19
0
 def buildDatafiles(self, dataFiles, databaseOsh):
     oshv = ObjectStateHolderVector()
     for dataFile in dataFiles:
         osh = self.buildDataFileOsh(dataFile)
         osh.setContainer(databaseOsh)
         oshv.add(osh)
     return oshv
Ejemplo n.º 20
0
def disLinux(hostObj, client, Framework=None, langBund=None, packageToCmdLine=None, cmdLineToInstalledSoftware=None):

    myVec = ObjectStateHolderVector()
    cmd = "rpm -qa --qf '%{NAME}~%{VERSION}~%{GROUP}~%{VENDOR}~%{installtime:date}~%{INSTALLTID}\\n'"
    r = client.execCmd(cmd, client.getDefaultCommandTimeout() * 4)  # V@@CMD_PERMISION tty protocol execution
    if r == None:
        return myVec

    lines = ""
    if re.search("\r\n", r):
        lines = r.split("\r\n")
    elif re.search("\n", r):
        lines = r.split("\n")
    else:
        return myVec
    if len(lines) == 0 or r.strip() == "":
        return myVec
    for line in lines:
        token = line.split("~")
        if token == None or len(token) < 3:
            continue
        # Does the package not have a vendor?  If so, make blank
        if len(token) == 3:
            token.append("")
        if token[0]:
            softwareOSH = hostresource.makeSoftwareOSH2(
                createHostOSH(hostObj), token[0], token[3], token[1], "", token[5], token[2], token[4]
            )

            if packageToCmdLine != None and cmdLineToInstalledSoftware != None and token[0] in packageToCmdLine:
                cmdLineToInstalledSoftware[packageToCmdLine[token[0]]] = softwareOSH

            myVec.add(softwareOSH)

    return myVec
Ejemplo n.º 21
0
 def buildBackupFiles(self, backupFiles, databaseOsh):
     oshv = ObjectStateHolderVector()
     for backupFile in backupFiles:
         osh = self._buildBackupFileOsh(backupFile)
         osh.setContainer(databaseOsh)
         oshv.add(osh)
     return oshv
Ejemplo n.º 22
0
def processVlanPortMap(portVlanIdMap):
    try:
        returnOSHV = ObjectStateHolderVector()
        if portVlanIdMap:
            for portVlanIdMapKey in portVlanIdMap.keys():
                vlanNameAndId = portVlanIdMapKey.split(':;:')
                vlanName = vlanNameAndId[0]
                vlanID = vlanNameAndId[1]
                ## Build VLAN OSH
                if vlanName and vlanName != 'N/A' and vlanID and vlanID != '-1' and type(eval(vlanID)) == type(1):
                    ## Get a list of port IDs from the port OSH list in this map
                    portOshList = portVlanIdMap[portVlanIdMapKey]
                    portIdList = []
                    for portOSH in portOshList:
                        portIdList.append(str(portOSH.getAttributeValue('port_index')))
                    portIdList.sort()

                    ciscoworks_utils.debugPrint(2, '[' + SCRIPT_NAME + ':processVlanPortMap] Got VLAN <%s> with <%s> ports, total VLANs <%s>' % (portVlanIdMapKey, len(portIdList), len(portVlanIdMap)))
                    vlanUniqueID = str(hash(':'.join(portIdList)))
                    if not vlanUniqueID:
                        vlanUniqueID = 1
                    #vlanOSH = modeling.createVlanOsh(vlanID, None, portIdList)
                    vlanOSH = ObjectStateHolder('vlan')
                    ciscoworks_utils.populateOSH(vlanOSH, {'name':vlanName, 'vlan_aliasname':vlanName, 'vlan_id':int(vlanID), 'vlan_unique_id':vlanUniqueID})
                    returnOSHV.add(vlanOSH)

                    ## Add a member link between this VLAN and all ports related to it
                    for portOSH in portOshList:
                        returnOSHV.add(modeling.createLinkOSH('membership', vlanOSH, portOSH))
        return returnOSHV
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.warn('[' + SCRIPT_NAME + ':processVlanPortMap] Exception: <%s>' % excInfo)
        pass
def DiscoveryMain(Framework):
    resultVector = ObjectStateHolderVector()

    ipAddress = Framework.getDestinationAttribute(DestinationProperty.IP_ADDRESS)
    credentialsId = Framework.getDestinationAttribute(DestinationProperty.CREDENTIALS_ID)
    hypervisorCmdbId = Framework.getDestinationAttribute(DestinationProperty.HYPERVISOR_CMDB_ID)
    esxCmdbId = Framework.getDestinationAttribute(DestinationProperty.ESX_CMDB_ID)
    esxBiosUuid = Framework.getDestinationAttribute(DestinationProperty.ESX_BIOS_UUID)
    
    if not esxBiosUuid:
        msg = "ESX BIOS UUID from trigger data is empty"
        errorObject = errorobject.createError(errorcodes.INTERNAL_ERROR_WITH_PROTOCOL_DETAILS, [cim.Protocol.DISPLAY, msg], msg)
        logger.reportErrorObject(errorObject)
        logger.error(msg)
        return resultVector
    
    try:
        unitaryComputerSystem = discoverEsxInventory(ipAddress, credentialsId, esxBiosUuid, Framework)
        
        inventoryResultVector = reportEsxInventory(unitaryComputerSystem, esxCmdbId)
        resultVector.addAll(inventoryResultVector)
        
        virtualMachines = discoverEsxVirtualTopology(ipAddress, credentialsId, esxBiosUuid, Framework)
        if virtualMachines:
            virtualResultVector = reportVirtualTopology(virtualMachines, hypervisorCmdbId)
            resultVector.addAll(virtualResultVector)
        
    except JException, ex:
        msg = ex.getMessage()
        msg = cim_discover.translateErrorMessage(msg)
        logger.debug(msg)
        errormessages.resolveAndReport(msg, cim.Protocol.DISPLAY, Framework)
Ejemplo n.º 24
0
def getVolumes(cinderApi, regionName, region_osh, zoneOshDict, serverOshDict):
    vector = ObjectStateHolderVector()
    volume_discoverer = openstack_discoverer.VolumeDiscoverer(cinderApi, regionName)
    volumes = volume_discoverer.discover()
    for volume in volumes:
        vector.addAll(volume.report(region_osh, zoneOshDict, serverOshDict))
    return vector
Ejemplo n.º 25
0
def report_tree(framework, business_object_node, parent_osh):
    vector = ObjectStateHolderVector()
    current_osh = business_object_node.create_osh(parent_osh)
    vector.add(current_osh)
    for node in business_object_node.get_children():
        vector.addAll(report_tree(framework, node, current_osh))
    return vector
Ejemplo n.º 26
0
def getSubnets(neutronApi, regionName, networkOshDict, openstack_osh):
    vector = ObjectStateHolderVector()
    subnet_discover = openstack_discoverer.SubnetDiscoverer(neutronApi, regionName)
    subnets = subnet_discover.discover()
    for subnet in subnets:
        vector.addAll(subnet.report(networkOshDict, openstack_osh))
    return vector
Ejemplo n.º 27
0
def getIMSPrograms(ls,  IMSSubSysDict ):

    vector = ObjectStateHolderVector()
    # Query the mainframe for IMS Programs
    for subsystem in  IMSSubSysDict.keys():
        (sub,prefix,subsystemOSH) = IMSSubSysDict[subsystem]
        command =  concatenate(prefix,_DSP_IMS_TRN_ALL )
        output = ls.evExecImsCommand(subsystem, command)
        if output.isSuccess() and len(output.cmdResponseList) > 0:
            firstlinelist = []
            for line in output.cmdResponseList:
                if (re.search('TRAN\s+CLS', line)  or  re.search('IEE600I', line) or  re.search('DFS996I', line) or  re.search('DFS4444I', line) or  re.search('\*\d+\/\d+\*', line)):
                    continue
                m = re.search('DFS000I',line)
                if m:
                    #logger.debug (' Non SSI Parsing  ')
                    SSIflag = 0
                    #logger.debug (line)
                    if re.search('PSBNAME:', line):
                        secondlinelist = line.split()
                        programname = secondlinelist[2]
                        vector.addAll (createProgramTransactionOsh(firstlinelist, programname,SSIflag, subsystemOSH))
                    else:
                        firstlinelist =  line.split()
                else:
                    #logger.debug (' SSI Parsing ')
                    SSIflag = 1
                    #logger.debug (line)
                    if re.search('PSBNAME:', line):
                        secondlinelist = line.split()
                        programname = secondlinelist[1]
                        vector.addAll (createProgramTransactionOsh(firstlinelist, programname, SSIflag, subsystemOSH))
                    else:
                        firstlinelist =  line.split()
    return vector
Ejemplo n.º 28
0
def DiscoveryMain(Framework): 
    warningsList = []
    errorsList = []
    oshvector = ObjectStateHolderVector()
    errobj = errorobject.INTERNAL_ERROR
    client = None

    ip_address = Framework.getDestinationAttribute('ip_address')
    ip_domain = Framework.getDestinationAttribute('ip_domain')
    credentials = netutils.getAvailableProtocols(Framework, protocolName, ip_address, ip_domain)  
  
    if len(credentials) == 0:
        msg = errormessages.makeErrorMessage(protocolName, pattern=errormessages.ERROR_NO_CREDENTIALS)
        errobj = errorobject.createError(errorcodes.NO_CREDENTIALS_FOR_TRIGGERED_IP, [protocolName], msg)
        warningsList.append(errobj)
        logger.debug(msg)
    else: 
        try:
            logger.info('Starting AS400 Connection.')
            for credential in credentials:
                client = Framework.createClient(credential)
                dicoverer = AS400Dicoverer(client)
                dicoverer.discover()
                oshvector.addAll(dicoverer.buildTopology())
        except NoClassDefFoundError, error:
            # Trying to catch if as400 java package is not found
            msg = error.getMessage()
            if re.search("as400", msg, re.I):
                processException(errorsList,warningsList,"Third party library is not found. Please read the documentation about prerequisites for this job.")
            else:
                processException(errorsList,warningsList, msg)
        except:
Ejemplo n.º 29
0
def createOwnerShip(scp_id, serverOsh):
    OSHVResult = ObjectStateHolderVector()
    scpOsh = ObjectStateHolder('scp', CmdbObjectID.Factory.restoreObjectID(scp_id))
    ownershiplinkOsh = modeling.createLinkOSH('ownership', serverOsh, scpOsh)
    OSHVResult.add(scpOsh)
    OSHVResult.add(ownershiplinkOsh)
    return OSHVResult
Ejemplo n.º 30
0
 def report(self, container):
     vector = ObjectStateHolderVector()
     zone_osh = ObjectStateHolder('openstack_zone')
     zone_osh.setStringAttribute('name', self.name)
     zone_osh.setContainer(container)
     vector.add(zone_osh)
     return zone_osh, vector
Ejemplo n.º 31
0
    def report(self, fcPort, containerOsh):
        '''
        @param fcPort: fcPort DO
        @param containerOsh: osh of corresponding container
        @return: tuple (fcport Osh, OSHV)
        @raise ValueError: Container is missing
        '''
#        if not containerOsh:
#            raise ValueError('Container for fcPort is not specified')
        fcPortOsh = self.builder.build(fcPort)
        if containerOsh:
            fcPortOsh.setContainer(containerOsh)
        vector = ObjectStateHolderVector()
        vector.add(fcPortOsh)
        return (fcPortOsh, vector)
Ejemplo n.º 32
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()

    (vec, errStr) = TTY_Connection_Utils.mainFunction(Framework)
    logger.debug('OSHVector contains ', vec.size(), ' objects.')
    # just in case we couldnt do any connection
    if vec.size() == 0:
        logger.debug('Failed to connect, No Host CI will be created')
        if (errStr == None or errStr.strip() == ''):
            Framework.reportError('Discovery failed due to internal error')
        else:
            Framework.reportWarning(errStr)
    else:
        OSHVResult.addAll(vec)
    return OSHVResult
Ejemplo n.º 33
0
def reportTopology(config, container_osh):
    vector = ObjectStateHolderVector()
    vector.add(container_osh)
    if config and container_osh:
        config_osh = buildFirewallConfig(config, container_osh)
        config_osh.setContainer(container_osh)
        vector.add(config_osh)

    if config and config.endpoints:
        vector.addAll(buildEndpoints(config.endpoints, container_osh))
    logger.debug('Networks %s' % config.nated_networks)
    if config and config.nated_networks:
        vector.addAll(reportNatedNetworks(config.nated_networks,
                                          container_osh))
    return vector
def DiscoveryMain(Framework):
	OSHVResult = ObjectStateHolderVector()	
	ipAddress = Framework.getDestinationAttribute('ip_address')
	credentialsId = Framework.getDestinationAttribute('credentialsId')
	hostId = Framework.getDestinationAttribute('hostId')
	
	hostOsh = ms_exchange_utils.restoreHostById(hostId)
	hostName = Framework.getDestinationAttribute('hostName')	
	if not hostName or hostName == 'N/A':
		hostName = ms_exchange_utils.getHostNameFromWmi(Framework)
	
	if not hostName:
		errobj = errorobject.createError(errorcodes.FAILED_GETTING_INFORMATION_NO_PROTOCOL, ['host name'], 'Failed to obtain host name')
		logger.reportErrorObject(errobj)
		return
	
	props = Properties()
	props.put(AgentConstants.PROP_WMI_NAMESPACE, WMI_NAMESPACE)	
	try:
		wmiClient = Framework.createClient(props)
		wmiAgent = WmiAgent(wmiClient, Framework)
		try:
			discoverExchangeServer(wmiAgent, ipAddress, credentialsId, OSHVResult, Framework, hostOsh, hostName)
		finally:			
			wmiClient.close()
	except Exception, ex:
		message = ex.getMessage()
		if (re.search("Invalid\sclass", message)):
			message = 'Unable to get Exchange data from WMI'
		logger.debugException(message)
		errormessages.resolveAndReport(message, WMI_PROTOCOL, Framework)
Ejemplo n.º 35
0
def DiscoveryMain(Framework):

	credentialsId = Framework.getDestinationAttribute('credentialsId')

	OSHVResult = ObjectStateHolderVector()
	matchers = SiebelAgent.SIEBEL_DEFAULT_ENTERPRISE_MATCHERS
	ip = Framework.getDestinationAttribute('ip_address')
	port = Framework.getDestinationAttribute('port')
	if port == 'NA':
		port = None

	try:
		client = None
		try:
			client = siebel_common.createClient(Framework, ip, matchers, credentialsId, port)
			username = client.getUserName()
			enterprise = client.getEnterprise()

			siteOSH = ObjectStateHolder('siebel_site')
			siteOSH.setAttribute('data_name', enterprise)
			siteOSH.setAttribute('gateway_address', ip)
			modeling.setAppSystemVendor(siteOSH)

			start_srvrmgr_discovery(client, ip, username, enterprise, siteOSH, Framework, OSHVResult)

		finally:
			if client is not None:
				client.close()
	except Exception, ex:
		strException = str(ex.getMessage())
		errormessages.resolveAndReport(strException, PROTOCOL_NAME, Framework)
		logger.debugException('')
Ejemplo n.º 36
0
def _discoverWindowsDeviceDriver(powershell, hostOsh):
    '''PowerShell, osh -> vector
    @raise Exception: failed getting windows driver by WMI
    '''
    vector = ObjectStateHolderVector()
    HR_Dis_Driver_Lib.discoverDriverByWmi(powershell, vector, hostOsh)
    return vector
Ejemplo n.º 37
0
def processWsdl(wsdl_url,
                Framework,
                wsdl_url_data=None,
                importWsdlDocuments=1,
                containerOSH=None):
    ucmdbVersion = Version().getVersion(Framework)
    locator = resource_locator.getProbeResourceLocator(ucmdbVersion)
    webserviceFolder = 'webservice'
    System.setProperty("wasp.location",
                       locator.contentLibPathOf(webserviceFolder))
    importWsdldNames = []
    importWsdldNameToData = {}

    OSHVResult = ObjectStateHolderVector()

    try:
        result = readWSDL(wsdl_url, wsdl_url_data, importWsdlDocuments)
        wsdl_url_data = result[0]
        defintion = result[1]
    except UnknownHostException, ex:
        host = ex.getMessage()
        msg = "Unknown host: %s" % host
        logger.debugException("Failed reading url: '%s', reason: '%s'\n" %
                              (wsdl_url, msg))
        errormessages.resolveAndReport(msg, ClientsConsts.HTTP_PROTOCOL_NAME,
                                       Framework)
        return OSHVResult
Ejemplo n.º 38
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()

    # create LPAR node
    hostId = Framework.getDestinationAttribute(PARAM_HOST_ID)
    lparOsh = None
    if eview400_lib.isNotNull(hostId):
        lparOsh = modeling.createOshByCmdbIdString('host_node', hostId)

    ls = eview400_lib.EvShell(Framework)
    (iseriesObjectOSHV) = processiSeriesObjects(ls, lparOsh, Framework)
    OSHVResult.addAll(iseriesObjectOSHV)

    ls.closeClient()

    return OSHVResult
Ejemplo n.º 39
0
def DiscoveryMain(Framework):
    Framework = jee_connection.EnhancedFramework(Framework)
    port = entity.WeakNumeric(int)
    port.set(Framework.getDestinationAttribute('port'))
    version = Framework.getDestinationAttribute('version')

    resultVector = ObjectStateHolderVector()
    isAppResourcesDiscoveryEnabled = Boolean.valueOf(
        Framework.getParameter('discoverAppResources'))
    isJMSResourcesDiscoveryEnabled = Boolean.valueOf(
        Framework.getParameter('discoverJMSResources'))
    discoverDeployedOnlyApplications = Boolean.valueOf(
        Framework.getParameter("discoverDeployedOnlyApplications"))
    protocolType = (Framework.getDestinationAttribute('protocol')
                    or ClientsConsts.HTTP_PROTOCOL_NAME)

    properties = Properties()
    properties.put(CollectorsConstants.PROTOCOL_ATTRIBUTE_PORT,
                   str(port.value()))
    properties.put(AgentConstants.VERSION_PROPERTY, version)
    properties.put(AgentConstants.PROP_WEBLOGIC_PROTOCOL, protocolType)

    platform = jee.Platform.WEBLOGIC

    try:
        client = Framework.createClient(properties)
    except (Exception, JException), exc:
        logger.warnException("Failed to establish connection")
        jee_connection.reportError(Framework, str(exc), platform.getName())
Ejemplo n.º 40
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    try:
        hostId = Framework.getDestinationAttribute('hostId')
        hostOsh = modeling.createOshByCmdbIdString('host_node', hostId)

        snmpClient = Framework.createClient()
        try:
            cssDiscoverer = createCssDiscoverer(snmpClient, Framework,
                                                OSHVResult, hostOsh)
            cssDiscoverer.discoverContentRules()
            cssDiscoverer.discoverServices()
        finally:
            snmpClient.close()
    except NoCssException:
        errobj = errorobject.createError(
            errorcodes.CSS_NOT_FOUND_ON_TARGET_HOST, None,
            'CSS was not found on target host')
        logger.reportErrorObject(errobj)
    except:
        errorMessage = logger.prepareJythonStackTrace('')
        logger.error(errorMessage)
        errormessages.resolveAndReport(errorMessage, 'SNMP', Framework)

    return OSHVResult
Ejemplo n.º 41
0
def osh_createNetworkOsh(lparOsh, tcpStacks):
    # tcpStacks  [ip, network, mask, interface name, status, type, mac address]
    _vector = ObjectStateHolderVector()
    for mac, tcpentry in tcpStacks.items():
        networkAddress = tcpentry[1].strip()
        ipAddress = tcpentry[0].strip()
        mask = tcpentry[2].strip()
        ipOsh = modeling.createIpOSH(ipAddress)
        netOsh = modeling.createNetworkOSH(networkAddress, mask)
        memberOsh = modeling.createLinkOSH('membership', netOsh, lparOsh)
        _vector.add(lparOsh)
        _vector.add(netOsh)
        _vector.add(memberOsh)
        memberOsh = modeling.createLinkOSH('membership', netOsh, ipOsh)
        _vector.add(memberOsh)
    return _vector
Ejemplo n.º 42
0
def _reportInstPfLinks(instOshs, pfNameToOsh, system):
    '@types: iterable[osh], dict[str, osh], System -> oshv'
    vector = ObjectStateHolderVector()
    systemName = system.getName()
    for inst_osh in instOshs:
        getProfilesForInstance(systemName, inst_osh, pfNameToOsh, vector)
    return vector
Ejemplo n.º 43
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    WEBSERVER_ID = Framework.getDestinationAttribute('id')
    installPath = Framework.getDestinationAttribute('installPath')
    client = None
    # since install path is the full path name to the process executable image
    # including the image name - separate the executable image name from its
    # directory path.
    # We need here only the path to the directory wehere the process resides
    m = re.search('(.*/)([^/]+)', installPath)
    if (m != None):
        installPath = m.group(1)
    try:
        try:
            client = Framework.createClient()
            rootPath = findRootPath(installPath)
            logger.debug('found rootPath: ', rootPath)
            if rootPath != None:
                discoverITS(client, rootPath, WEBSERVER_ID, OSHVResult)
            else:
                logger.error('Can not find the ITS root path')
        except:
            errorMsg = str(sys.exc_info()[1])
            logger.debugException(errorMsg)
            errormessages.resolveAndReport(errorMsg, 'NTCMD', Framework)
    finally:
        if (client != None):
            try:
                client.close()
            except:
                logger.debug('Failed to execute disconnect NTCMD..')

    return OSHVResult
Ejemplo n.º 44
0
def DiscoveryMain(Framework):
    resultVector = ObjectStateHolderVector()

    try:
        configurationReader = nnmi.ConfigurationReader(Framework)
        configuration = configurationReader.getConfiguration()

        connectionFactory = nnmi.ConnectionFactory(Framework)
        connections = connectionFactory.getConnections()

        if connections:
            if len(connections) > 1:
                logger.debug(
                    "More than one set of credentials found, the first one is used"
                )

            connection = connections[0]

            strategy = nnmi.getDiscoveryStrategy(Framework, configuration)

            strategy.discover(connection)

    except nnmi.IntegrationException, ex:
        msg = str(ex)
        logger.error(msg)
        errormessages.resolveAndReport(msg, nnmi.NNM_PROTOCOL_NAME, Framework)
Ejemplo n.º 45
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    protocol = Framework.getDestinationAttribute('Protocol')
    try:
        csvFileName = Framework.getRequiredParameterValue(PARAM_CSV_FILE)
        delimiter = Framework.getRequiredParameterValue(
            PARAM_CSV_FILE_DELIMITER)
        if delimiter and delimiter.isdigit():
            delimiter = chr(int(delimiter))
        rowToStartIndex = Framework.getRequiredParameterValue(
            PARAM_ROW_TO_START_INDEX)
        bulkSize = Framework.getParameter(import_utils.PARAM_BULK_SIZE)
        flushObjects = Framework.getParameter(import_utils.PARAM_FLUSH_OBJECTS)
        fileEncoding = Framework.getParameter(import_utils.PARAM_FILE_ENCODING)

        dataSource = CsvFileDataSource(csvFileName, delimiter,
                                       int(rowToStartIndex), Framework,
                                       fileEncoding)
        dataSource.quoteSymbol = Framework.getParameter(PARAM_QUOTE_SYMBOL)

        if flushObjects and (flushObjects.lower() == "true"):
            import_utils.importFlushingCis(dataSource, OSHVResult, Framework,
                                           bulkSize)
        else:
            import_utils.importCis(dataSource, OSHVResult, Framework)

    except Exception, ex:
        exInfo = ex.getMessage()
        errormessages.resolveAndReport(exInfo, protocol, Framework)
Ejemplo n.º 46
0
def DiscoveryMain(framework, credsManager, credsId, instNr, clientNr,
                  sysNames):
    '@types: RichFramework, CredsManager, str, str, str, set[str] -> oshv'
    config = _build_config(framework, credsId, instNr, clientNr)
    vector = ObjectStateHolderVector()
    warnings = []
    with closing(_establishConnection(framework, config)) as client:
        loadServers = saputils.SapUtils.SERVERS_LOAD
        sapUtils = saputils.SapUtils(client, loadType=loadServers)
        # get system information from CCMS
        systemName = getSapSystemName(sapUtils)
        if systemName in sysNames:
            msg = "Connected to system %s that is already discovered"
            logger.warn(msg % systemName)
            return vector
        domain = config.domain
        hostname = config.hostname
        connInfo = ConnectionInfo(config.ip_address, instNr, credsId)
        t = discoverTopology(sapUtils, domain, hostname, connInfo)
        vector, warnings_ = t
        if warnings_:
            warnings.extend(warnings_)
        # cache visited sap system
        sysNames.add(systemName)
    return vector, warnings
Ejemplo n.º 47
0
def DiscoveryMain(Framework):
    logger.reportWarning(
        'The job is deprecated. Use "Network Connectivity Data Analyzer" instead.'
    )
    #	netlinks = NetlinksPotentialServers(Framework)
    #	netlinks.discover()
    return ObjectStateHolderVector()
Ejemplo n.º 48
0
def DiscoveryMain(framework, creds_manager):
    config = _build_config(framework)
    vector, warnings = ObjectStateHolderVector(), []
    with closing(_establish_connection(framework, config)) as client:
        for result in _discoverAbapSystemTopology(client, config, framework):
            consume_results(vector, warnings, result)
    return vector, warnings
Ejemplo n.º 49
0
 def reportStoreDependencyOnDatasource(self, container, store, datasource):
     r''' Reports linkage between JMS Store and any type of datasource,
     like JDBC store and database datasource.
     @note: Store will be built if it wasn't previously
     @types: entity.HasOsh, jms.Store, entity.HasOsh -> ObjectStateHolderVector
     @param container: JMS Store container in case if store is not built
     '''
     if not store:
         raise ValueError("Store is not specified")
     if not (datasource and datasource.getOsh()):
         raise ValueError("Datasource is not specified or not built")
     vector = ObjectStateHolderVector()
     storeOsh = store.getOsh() or store.build(self.builder())
     vector.add(
         modeling.createLinkOSH('depend', storeOsh, datasource.getOsh()))
     return vector
Ejemplo n.º 50
0
def reportChassis(hostDo, fsm_osh):
    if not fsm_osh:
        raise ValueError('Failed to report Chassis. No FSM OSH passed')
    vector = ObjectStateHolderVector()
    chassis_osh = buildChassis(hostDo)
    link_osh = modeling.createLinkOSH('manage', fsm_osh, chassis_osh)
    vector.add(link_osh)
    if hostDo.ipList:
        for ip in hostDo.ipList:
            ip_osh = modeling.createIpOSH(ip)
            link_osh = modeling.createLinkOSH('containment', chassis_osh,
                                              ip_osh)
            vector.add(ip_osh)
            vector.add(link_osh)
    vector.add(chassis_osh)
    return vector, chassis_osh
def DiscoveryMain(Framework):
    version = Framework.getDestinationAttribute('siebelVersion')
    siebelRootDir = Framework.getDestinationAttribute('siebelInstallDir')

    OSHVResult = ObjectStateHolderVector()
    appServerId = Framework.getDestinationAttribute('id')
    appServerOSH = modeling.createOshByCmdbIdString('siebel_app_server',
                                                    appServerId)
    modeling.setAppServerType(appServerOSH)

    client = None
    try:
        client = Framework.createClient()
        discoverConfigFile(siebelRootDir, appServerOSH, client, version,
                           OSHVResult)
    except:
        errmsg = 'Connection failed: %s' % str(sys.exc_info()[1]).strip()
        Framework.reportError(errmsg)
        logger.debugException(errmsg)

    if (client != None):
        try:
            client.close()
        except:
            pass

    return OSHVResult
Ejemplo n.º 52
0
def DiscoveryMain(Framework):

    protocolName = "NTCMD"

    OSHVResult = ObjectStateHolderVector()
    param = Framework.getParameter('discoverSoftware')
    if (param != None) and not Boolean.parseBoolean(param):
        logger.debug(
            'No discovery for software by NTCMD, parameter discoverSoftware is false'
        )
        return OSHVResult

    hostID = Framework.getDestinationAttribute('hostId')

    hostOSH = modeling.createOshByCmdbIdString('host', hostID)

    clientShUtils = None
    try:
        props = Properties()
        props.setProperty(AgentConstants.PROP_NTCMD_AGENT_COMMAND_TIMEOUT,
                          '100000')
        client = Framework.createClient(props)
        if client is None:
            raise Exception, 'Failed to create NTCMD client'
    except Exception, ex:
        strException = ex.getMessage()
        errormessages.resolveAndReport(strException, protocolName, Framework)
Ejemplo n.º 53
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    #ipAddress = Framework.getDestinationAttribute('ip_address')
    #credentialsId = Framework.getDestinationAttribute('credentialsId')
    hostId = Framework.getDestinationAttribute('hostId')

    try:
        factory = hyperv.ShellClientFactory(Framework)
        shell = None
        try:
            shell = factory.createClient()

            language = shell.getOsLanguage()
            bundle = hyperv.getBundleByLanguage(language, Framework)
            namespace = hyperv.ShellNamespaceLookUp().lookUp(shell)
            wmiProvider = hyperv.ShellHypervAgentProvider(
                shell, bundle, namespace)
            hyperv.discoverHypervHost(
                wmiProvider, hostId, Framework, OSHVResult,
                namespace[2:])  #strip heading slashes in namespace

        finally:
            if shell is not None:
                shell.closeClient()
    except JException, ex:
        exInfo = ex.getMessage()
        errormessages.resolveAndReport(exInfo, NTCMD_PROTOCOL, Framework)
Ejemplo n.º 54
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    logger.debug('Start nmap_osfingerprint.py')
    ip = Framework.getDestinationAttribute('ip_address')
    timeout = Framework.getParameter('nmap_host_timeout')
    if not str(timeout).isdigit():
        msg = "Timeout parameter value must be a digit"
        logger.debug(msg)
        errormessages.resolveAndReport(msg,
                                       ClientsConsts.LOCAL_SHELL_PROTOCOL_NAME,
                                       Framework)
        return OSHVResult

    timeout = int(timeout) * 1000
    scanKnownPortsOnly = Boolean.parseBoolean(
        Framework.getParameter('scan_known_ports_only'))
    portstoscan = Framework.getParameter('scan_these_ports_only')
    doServiceFingerprints = Boolean.parseBoolean(
        Framework.getParameter('Perform_Port_Fingerprints'))
    createApp = Boolean.parseBoolean(
        Framework.getParameter('Create_Application_CI'))
    discoverOsName = Boolean.parseBoolean(
        Framework.getParameter('discover_os_name'))
    nmapLocation = Framework.getParameter('nmap_location')
    #discover_UDP_Ports	= int(Framework.getParameter('Discover_UDP_Ports'))
    discoverUdpPorts = 0

    agent_root_dir = CollectorsParameters.BASE_PROBE_MGR_DIR
    agent_ext_dir = agent_root_dir + CollectorsParameters.getDiscoveryResourceFolder(
    ) + CollectorsParameters.FILE_SEPARATOR
    tmp_file_name = agent_ext_dir + string.replace(
        ip, '.', '_') + time.strftime("%H%M%S", time.gmtime(
            time.time())) + 'nmap.xml'

    syncNmapPortConfigFile(agent_root_dir)

    logger.debug('temp file for storing nmap results: ', tmp_file_name)
    try:
        client = Framework.createClient(
            ClientsConsts.LOCAL_SHELL_PROTOCOL_NAME)
        try:
            performNmapDiscover(client, ip, tmp_file_name, timeout,
                                agent_ext_dir, scanKnownPortsOnly, portstoscan,
                                doServiceFingerprints, discoverUdpPorts,
                                nmapLocation)
            if os.path.exists(tmp_file_name):
                logger.debug('start processing the nmap results')
                processNmapResult(tmp_file_name, OSHVResult, discoverOsName,
                                  doServiceFingerprints, createApp, Framework)
            else:
                raise ValueError, 'Error nmap result file is missing: %s' % tmp_file_name
        finally:
            client.close()
            File(tmp_file_name).delete()
    except Exception, e:
        msg = str(e.getMessage())
        logger.debug(msg)
        errormessages.resolveAndReport(msg,
                                       ClientsConsts.LOCAL_SHELL_PROTOCOL_NAME,
                                       Framework)
Ejemplo n.º 55
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()

    ip_address = Framework.getDestinationAttribute('ip_address')

    hostOSH = modeling.createHostOSH(ip_address)

    protocols = Framework.getAvailableProtocols(
        ip_address, ClientsConsts.SQL_PROTOCOL_NAME)

    for sqlProtocol in protocols:
        dbClient = None
        try:
            try:
                if dbutils.protocolMatch(Framework, sqlProtocol, 'sybase',
                                         None, None) == 0:
                    continue

                dbClient = Framework.createClient(sqlProtocol)
                logger.debug('Connnected to sybase on ip ',
                             dbClient.getIpAddress(), ', port ',
                             str(dbClient.getPort()), ' to database ',
                             dbClient.getDatabaseName(), 'with user ',
                             dbClient.getUserName())
                dbversion = dbClient.getDbVersion()

                logger.debug('Found sybase server of version:', dbversion)
                res = dbClient.executeQuery(
                    "select srvnetname from master..sysservers where srvid = 0"
                )  #@@CMD_PERMISION sql protocol execution
                if res.next():
                    dbname = string.strip(res.getString(1))
                    sybasedOSH = modeling.createDatabaseOSH(
                        'sybase', dbname, str(dbClient.getPort()),
                        dbClient.getIpAddress(), hostOSH, sqlProtocol,
                        dbClient.getUserName(), None, dbversion)
                    OSHVResult.add(sybasedOSH)
                else:
                    Framework.reportWarning('Sybase server was not found')
            except MissingJarsException, e:
                logger.debugException(e.getMessage())
                Framework.reportError(e.getMessage())
                return
            except:
                logger.debugException(
                    'Failed to discover sybase with credentials ', sqlProtocol)
        finally:
Ejemplo n.º 56
0
def StepMain(Framework):
    consumers = Framework.getProperty(DependenciesDiscoveryConsts.NEXT_HOP_PROVIDERS_RESULT_PROPERTY)
    OSHVResult = ObjectStateHolderVector()
    if (consumers is not None) and (consumers.size() > 0):
        ipPortconcepts = HashMap()

        localShell = None
        try:
            dnsServers = Framework.getParameter('dnsServers') or None

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

            localShell = shellutils.ShellUtils(Framework.createClient(ClientsConsts.LOCAL_SHELL_PROTOCOL_NAME))

            #going through extracted consumers
            for i in range(0, consumers.size()):
                consumer = consumers.get(i)
                depedencies = consumer.getDependencies()
                #going through dependencies of consumer
                for depedency in depedencies:
                    variables = depedency.getExportVariables()
                    #going through extracted variables of dependency
                    for variable in variables:
                        variableName = variable.getName()
                        values = variable.getValues()
                        conceptDefinition = variableName.split('.')
                        if (len(conceptDefinition) == 2) and len(conceptDefinition[0]) and ((conceptDefinition[1].upper() == PROVIDER_IP) or (conceptDefinition[1].upper() == PROVIDER_PORT)):
                            processIpPortConcept(ipPortconcepts, conceptDefinition[0].upper(), conceptDefinition[1].upper(), values)
                        elif variableName.upper() == PROVIDER_IP:
                            processIps(Framework, OSHVResult, values, localShell, dnsServers)

            resolveIpFromDnsPortipPortconcepts(Framework, OSHVResult, ipPortconcepts, localShell, dnsServers)
            Framework.sendObjects(OSHVResult)
            Framework.flushObjects()
        except:
            Framework.reportError(logger.prepareJythonStackTrace(''))
            Framework.setStepExecutionStatus(WorkflowStepStatus.FATAL_FAILURE)

        if localShell is not None:
            try:
                localShell.close()
                localShell = None
            except:
                pass
    Framework.getState().setProperty(DependenciesDiscoveryConsts.NEXT_HOP_PROVIDERS_RESULT_PROPERTY, not OSHVResult.isEmpty())
    Framework.setStepExecutionStatus(WorkflowStepStatus.SUCCESS)
Ejemplo n.º 57
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    oracleId = Framework.getDestinationAttribute('id')

    credentialsId = Framework.getDestinationAttribute('credentialsId')

    instanceName = Framework.getDestinationAttribute('sid')
    protocolDbSid = Framework.getProtocolProperty(
        credentialsId, CollectorsConstants.SQL_PROTOCOL_ATTRIBUTE_DBSID, 'NA')

    try:
        #in some cases sid does not coinside to the instance name, so real sid should be used
        #e.g. when sid is written down in a world unique identifiing string format <instance name>.fulldomainname
        oracleClient = None
        if protocolDbSid and protocolDbSid != 'NA' and protocolDbSid != instanceName:
            try:
                props = Properties()
                props.setProperty(Protocol.SQL_PROTOCOL_ATTRIBUTE_DBSID,
                                  protocolDbSid)
                oracleClient = Framework.createClient(props)
            except:
                logger.debug(
                    'Failed to connect using sid defined in creds. Will try instance name as sid.'
                )
                oracleClient = None
        if not oracleClient:
            props = Properties()
            props.setProperty(Protocol.SQL_PROTOCOL_ATTRIBUTE_DBSID,
                              instanceName)
            oracleClient = Framework.createClient(props)

        try:
            configFileContent = getConfigFileContent(oracleClient)
        finally:
            oracleClient.close()

        oracleOsh = modeling.createOshByCmdbIdString('oracle', oracleId)
        configFileOsh = modeling.createConfigurationDocumentOSH(
            'init_parameters.ora', 'NA', configFileContent, oracleOsh,
            modeling.MIME_TEXT_PLAIN, None, FILE_DESCRIPTION)
        OSHVResult.add(configFileOsh)

    except Exception, ex:
        logger.debugException('')
        strException = ex.getMessage()
        errormessages.resolveAndReport(strException, SQL_PROTOCOL_NAME,
                                       Framework)
Ejemplo n.º 58
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()

    DebugMode = Framework.getParameter('DebugMode')
    userExtDir = CollectorsParameters.BASE_PROBE_MGR_DIR + CollectorsParameters.getDiscoveryResourceFolder(
    ) + '\\'

    filePathDir = userExtDir + 'TQLExport\\ARIS\\results\\'
    directory = File(filePathDir)
    files = directory.listFiles()

    if files == None:
        logger.warn(
            'Results XML not found. Perhaps no data was received from ARIS or an error occurred in the Pull_From_ARIS script.'
        )
        return

    try:
        ## Start the work
        for file in files:
            if file != None or file != '':
                builder = SAXBuilder()
                doc = builder.build(file)
                # Process CIs #
                info(
                    "Start processing CIs to update in the destination server..."
                )
                allObjects = doc.getRootElement().getChild('data').getChild(
                    'objects').getChildren('Object')
                (objVector, ciDict) = processObjects(allObjects)

                OSHVResult.addAll(objVector)
                # Process Relations #
                info(
                    "Start processing Relationships to update in the destination server..."
                )
                allLinks = doc.getRootElement().getChild('data').getChild(
                    'links').getChildren('link')
                linkVector = processLinks(allLinks, ciDict)
                OSHVResult.addAll(linkVector)
    except:
        stacktrace = traceback.format_exception(sys.exc_info()[0],
                                                sys.exc_info()[1],
                                                sys.exc_info()[2])
        info(concatenate('Failure: ():\n', stacktrace))

    if (DebugMode != None):
        DebugMode = DebugMode.lower()
        if DebugMode == "true":
            mam_utils.info(
                '[NOTE] UCMDB Integration is running in DEBUG mode. No data will be pushed to the destination server.'
            )
            print OSHVResult.toXmlString()
            return None
        else:
            #print OSHVResult.toXmlString()
            return OSHVResult
Ejemplo n.º 59
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    ipAddress = Framework.getDestinationAttribute('ip_address')
    hostname = Framework.getDestinationAttribute('hostname')
    if hostname is None:
        hostname = 'NA'
    else:
        hostname = hostname.upper()
    protocolType = Framework.getParameter('protocolType')
    hostOSH = modeling.createHostOSH(ipAddress)

    protocols = Framework.getAvailableProtocols(
        ipAddress, ClientsConsts.SQL_PROTOCOL_NAME)
    sidList = []
    for protocol in protocols:
        protocol_validation_status = isValidProtocol(Framework, protocol,
                                                     protocolType)
        if protocol_validation_status == PROTOCOL_NO_PORT:
            logger.debug('Protocol ', protocol, ' has no defined port')
        elif protocol_validation_status == PROTOCOL_NO_SID:
            logger.debug('Protocol ', protocol, ' has no defined SID')
        elif dbutils.protocolMatch(Framework, protocol, protocolType, None,
                                   None):
            logger.debugException('Trying to connect with protocol:', protocol)
            dbClient = None
            try:
                try:
                    dbClient = Framework.createClient(protocol)
                    sid = getDbSid(dbClient, hostname)
                    if sid is None:
                        continue
                    if ((sid in sidList) != 0):
                        logger.debug(
                            str('Database : ' + sid + ' already reported.'))
                        continue
                    databaseServer = createDatabaseOSH(
                        hostOSH, dbClient, sid, dbClient.getDbVersion(),
                        dbClient.getAppVersion())
                    OSHVResult.add(databaseServer)
                    sidList.append(sid)
                except SQLException, sqlex:
                    logger.debug(sqlex.getMessage())
                except:
                    msg = logger.prepareFullStackTrace('')
                    errormessages.resolveAndReport(
                        msg, ClientsConsts.SQL_PROTOCOL_NAME, Framework)
            finally:
Ejemplo n.º 60
0
def disSunOS(hostObj,
             client,
             Framework=None,
             langBund=None,
             packageToCmdLine=None,
             cmdLineToInstalledSoftware=None):

    myVec = ObjectStateHolderVector()
    r = client.execCmd('pkginfo -l',
                       client.getDefaultCommandTimeout() *
                       12)  # V@@CMD_PERMISION tty protocol execution
    if r == None:
        return myVec
    reg = langBund.getString(
        'sun_pkginfo_reg_pkginst_name_category_version_vendor')

    tokens = r.split('PKGINST')

    for token in tokens:
        currBuffer = 'PKGINST' + token

        res = re.search(reg, currBuffer, re.DOTALL)
        if res:
            swName = res.group(1)
            if swName:
                vendor = res.group(5) or ''
                if vendor:
                    vendor = vendor.strip()
                installDate = ''
                # Can be not fix the problem if from console was got already corrupted text
                if re.match('[\w\s/.,:-]+$', res.group(6)):
                    installDate = res.group(6)
                else:
                    logger.warn(
                        "Install software date attribute include non-English character. Ignored."
                    )
                softwareOSH = hostresource.makeSoftwareOSH2(
                    createHostOSH(hostObj), swName, vendor, res.group(4), '',
                    '', res.group(3), installDate)

                if swName and packageToCmdLine != None and cmdLineToInstalledSoftware != None and swName.strip(
                ) in packageToCmdLine:
                    cmdLineToInstalledSoftware[packageToCmdLine[
                        swName.strip()]] = softwareOSH

                myVec.add(softwareOSH)
    return myVec