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
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
def buildDatafiles(self, dataFiles, databaseOsh): oshv = ObjectStateHolderVector() for dataFile in dataFiles: osh = self.buildDataFileOsh(dataFile) osh.setContainer(databaseOsh) oshv.add(osh) 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)
def DiscoveryMain(Framework): resultCollection = ObjectStateHolderVector() hostId = Framework.getDestinationAttribute('hostId') hostIp = Framework.getDestinationAttribute('ip_address') nodeName = Framework.getDestinationAttribute('nodeName') client = None try: client = Framework.createClient() catalogUidToSqlMx = _discoverSqlMx(client, nodeName) catalogUidToMxSchema = {} if catalogUidToSqlMx: catalogUidToMxSchema = _discoverSqlMxSchemas(client) client.executeCmd('exit;', 0, 1) sqlmpList = _discoverSqlMp(client) client.executeCmd('exit;', 0, 1) hostOsh = modeling.createOshByCmdbIdString('host', hostId) resultCollection.add(hostOsh) _reportNonStopTopology(resultCollection, hostOsh, hostIp, catalogUidToSqlMx, catalogUidToMxSchema, sqlmpList) except Exception, ex: exInfo = ex.getMessage() errormessages.resolveAndReport(exInfo, ClientsConsts.SSH_PROTOCOL_NAME, Framework)
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
def disWinOS(host_obj, shell, Framework, langBund, softNameToInstSoftOSH=None): host = modeling.createOshByCmdbIdString("host", host_obj) resultsVector = ObjectStateHolderVector() if not NTCMD_HR_REG_Software_Lib.doSoftware(shell, host, resultsVector, softNameToInstSoftOSH): discoverSoftwareByWmic(shell, host, resultsVector, softNameToInstSoftOSH) wmiProvider = getWmiProvider(shell) hostDiscoverer = WmiHostDiscoverer(wmiProvider) if hostDiscoverer.isWin2008(): softwares = discover2008Hotfixes(wmiProvider, host) for software in softwares: if not software.osh: continue if softNameToInstSoftOSH is not None: if software.name in softNameToInstSoftOSH: continue softNameToInstSoftOSH[software.name] = software.osh resultsVector.add(software.osh) elif hostDiscoverer.isWindows8_2012(): softwares = discover2012Hotfixes(wmiProvider, host) for software in softwares: if not software.osh: continue if softNameToInstSoftOSH is not None: if software.name in softNameToInstSoftOSH: continue softNameToInstSoftOSH[software.name] = software.osh resultsVector.add(software.osh) softwareList = WindowsAppsDiscoverer(shell).discover() softwareOshVector = InstalledSoftwareReporter().reportAll(softwareList, host) resultsVector.addAll(softwareOshVector) return resultsVector
def DiscoveryMain(Framework): OSHVResult = ObjectStateHolderVector() # # Write implementation to return new result CIs here... ipList = Framework.getTriggerCIDataAsList('PHYSICAL_IP_ADDRESS') portList = Framework.getTriggerCIDataAsList('PHYSICAL_PORT') service_context = Framework.getDestinationAttribute('SERVICE_CONTEXT') service_type = Framework.getDestinationAttribute('SERVICE_TYPE') cluster_id = Framework.getDestinationAttribute('CLUSTER_ID') application_resource_id = Framework.getDestinationAttribute('APPLICATION_RESOURCE_ID') cluster_root_class = Framework.getDestinationAttribute('CLUSTER_CLASS') application_resource_class = Framework.getDestinationAttribute('APPLICATION_RESOURCE_CLASS') SCPId = Framework.getDestinationAttribute('id') clusterOsh = modeling.createOshByCmdbIdString(cluster_root_class, cluster_id) OSHVResult.addAll(scp.createCPLink(application_resource_id, application_resource_class, cluster_id, cluster_root_class, SCPId, service_context)) for index in range(len(ipList)): scpOsh = scp.createScpOsh(clusterOsh, service_type, ip=ipList[index], port=portList[index], context=service_context) ipOsh = modeling.createIpOSH(ipList[index]) OSHVResult.add(scpOsh) OSHVResult.add(ipOsh) return OSHVResult
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
def modelConnectedPortByPowerShell(context): endpointOSHV = ObjectStateHolderVector() try: logger.debug("reporting endpoints for iis using powershell") shell = NTCMD_IIS.CscriptShell(context.client) system32Location = shell.createSystem32Link() or '%SystemRoot%\\system32' discoverer = iis_powershell_discoverer.get_discoverer(shell) if isinstance(discoverer, iis_powershell_discoverer.PowerShellOverNTCMDDiscoverer): discoverer.system32_location = system32Location executor = discoverer.get_executor(shell) sites_info = iis_powershell_discoverer.WebSitesCmd() | executor for site_info in sites_info: site_name = site_info.get("name") if site_name: bindings = iis_powershell_discoverer.WebSiteBindingCmd(site_name) | executor host_ips = [] host_ips.append(context.application.getApplicationIp()) logger.debug("application ip", context.application.getApplicationIp()) parse_func = partial(iis_powershell_discoverer.parse_bindings, host_ips=host_ips) bindings = map(parse_func, bindings) for binding in bindings: logger.debug("reporting binding:", binding[2]) for bind in binding[2]: endpointOSH = visitEndpoint(bind) hostosh = context.application.getHostOsh() ip = bind.getAddress() hostosh = modeling.createHostOSH(ip) endpointOSH.setContainer(hostosh) linkOsh = modeling.createLinkOSH("usage", context.application.getOsh(), endpointOSH) endpointOSHV.add(endpointOSH) endpointOSHV.add(linkOsh) except Exception, ex: logger.debug("Cannot get port from powershell:", ex) return None
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
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 getCICSRegions(ls, subsystemOSH): regiondict = {} str_name = 'name' if UCMDB_VERSION < 9: str_name = 'data_name' vector = ObjectStateHolderVector() # Get the active jobs running on the lpar # Look for the program name , if it is DFHSIP then we have found an active CICS job # The job name is the CICS region output = ls.evSysInfoCmd(_CMD_F_ALL_JOBS,'40') if output.isSuccess() and len(output.cmdResponseList) > 0: for line in output.cmdResponseList: if isNotNull(line): splitline = line.split('|') if len(splitline) == 10: if splitline[9] == 'DFHSIP': region = splitline[0].strip() #logger.debug ('Found region ===> ',region) cicsRegionOSH = ObjectStateHolder('cics_region') cicsRegionOSH.setAttribute(str_name, region) cicsRegionOSH.setContainer(subsystemOSH) addInfoOnRegions(ls, cicsRegionOSH) if not(regiondict.has_key(region)): regiondict[region] = cicsRegionOSH vector.add(cicsRegionOSH) return vector, regiondict
def buildHosts(self): for host in self.hosts.values(): hostOSHV = ObjectStateHolderVector() hostOsh, hostVector = host.buildOshAndIps() hostOSHV.addAll(hostVector) hbaIdToOsh = {} for hba in host.hbas.values(): hbaOsh = hba.build() hbaOsh.setContainer(hostOsh) hbaIdToOsh[hba.hbaId] = hbaOsh self.addWwnOsh(hba.wwn, hbaOsh) hostOSHV.add(hbaOsh) for port in host.ports.values(): portOsh = port.build() portOsh.setContainer(hostOsh) self.portIdToOsh[port.portId] = portOsh if port.nodeId and port.nodeId in hbaIdToOsh.keys(): containmentLinkOsh = modeling.createLinkOSH('containment', hbaIdToOsh[port.nodeId], portOsh) hostOSHV.add(containmentLinkOsh) hostOSHV.add(portOsh) self.addWwnOsh(port.wwn, portOsh) for path in host.paths.values(): localVolumeOsh = self.storageArrays[self.volumeIdToStorageId[path.volumeId]].volumes[path.volumeId].build() localVolumeOsh.setContainer(hostOsh) dependencyLink = modeling.createLinkOSH('dependency', localVolumeOsh, self.volumeIdToOsh[path.volumeId]) hostOSHV.add(dependencyLink) hostOSHV.add(localVolumeOsh) hostOSHV.add(self.volumeIdToOsh[path.volumeId]) self.framework.sendObjects(hostOSHV) self.framework.flushObjects()
def DiscoveryMain(Framework): OSHVResult = ObjectStateHolderVector() jobId = Framework.getDiscoveryJobId() host_id = Framework.getDestinationAttribute('id') host_name = Framework.getTriggerCIData('host_name') dnsServers = Framework.getTriggerCIDataAsList('dnsServers') or None try: host_name = host_name.split(" ") ips = pi_utils.getIPs(host_name[0], Framework) if not ips: raise ValueError() hostOSH = modeling.createOshByCmdbIdString('node', host_id) modeling.addHostAttributes(hostOSH, None, host_name[0]) #OSHVResult.add(hostOSH) for ip in ips: ipRes = pi_utils.getIPOSHV(Framework, ip, None, dnsServers, False, True) if ipRes.size() > 0: OSHVResult.add( modeling.createLinkOSH('containment', hostOSH, modeling.createIpOSH(ip))) OSHVResult.addAll(ipRes) if OSHVResult.size() <= 0: raise ValueError() except Exception, e: msg = logger.prepareJythonStackTrace( "Error getting IPs for %s: " % (host_name), e) errormessages.resolveAndReport(msg, jobId, Framework) logger.error(msg)
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
def buildBackupFiles(self, backupFiles, databaseOsh): oshv = ObjectStateHolderVector() for backupFile in backupFiles: osh = self._buildBackupFileOsh(backupFile) osh.setContainer(databaseOsh) oshv.add(osh) return oshv
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
def DiscoveryMain(Framework): OSHVResult = ObjectStateHolderVector() # # Write implementation to return new result CIs here... ipList = Framework.getTriggerCIDataAsList('PHYSICAL_IP_ADDRESS') portList = Framework.getTriggerCIDataAsList('PHYSICAL_PORT') service_context = Framework.getDestinationAttribute('SERVICE_CONTEXT') service_type = Framework.getDestinationAttribute('SERVICE_TYPE') application_resource_id = Framework.getDestinationAttribute('APPLICATION_RESOURCE_ID') application_resource_class = Framework.getDestinationAttribute('APPLICATION_RESOURCE_CLASS') junction_id = Framework.getDestinationAttribute('JUNCTION_ID') junction_root_class = Framework.getDestinationAttribute('JUNCTION_CLASS') junction_name = Framework.getDestinationAttribute('JUNCTION_NAME') SCPId = Framework.getDestinationAttribute('id') junctionOsh = modeling.createOshByCmdbIdString(junction_root_class, junction_id) url = urlparse(service_context) if url: # get context root path from url path = url.path if path.startswith(junction_name + '/'): logger.info('Create one consumer-provider link between application and junction') OSHVResult.addAll(scp.createCPLink(application_resource_id, application_resource_class, junction_id, junction_root_class, SCPId, service_context)) for index in range(len(ipList)): scpOsh = scp.createScpOsh(junctionOsh, service_type, ip=ipList[index], port=portList[index], context=service_context) logger.info('Create scp with ip %s and port %s' % (ipList[index], portList[index])) ipOsh = modeling.createIpOSH(ipList[index]) OSHVResult.add(scpOsh) OSHVResult.add(ipOsh) return OSHVResult
def processData(ipMap, ndMap, ifMap, nwMap, l2Map, vlMap, ptMap, cdMap, hostIpMap, hostIfMap, connectionIfMap, discoverNonL2Devices, Framework): _vector = ObjectStateHolderVector() ifOshMap = {} portOshMap = {} cardOshMap = {} hostOSH = None for (hostId, hostObj) in ndMap.items(): if hostIpMap.has_key(hostId): ipList = hostIpMap[hostId] if len(ipList) > 0: # if IPs available create host with the first IP hostOSH = createHost(discoverNonL2Devices, hostId, ndMap, '', ipMap[ipList[0]].ipValue) if notNull(hostOSH): _vector.add(hostOSH) # create IP CIs _vector = processIpsAndSubnets(_vector, hostIpMap, hostId, ipMap, nwMap, hostOSH) ## create interfaces (_vector, ifOshMap) = processInterfaces(_vector, ifOshMap, hostIfMap, hostId, ifMap, hostOSH) ## create hardware boards (_vector, cardOshMap) = processCards(_vector, cardOshMap, cdMap, hostOSH, hostId) ## create ports (_vector, portOshMap) = processPorts(_vector, portOshMap, ptMap, ifOshMap, cardOshMap, hostOSH, hostId) # add l2 connection objects _vector.addAll(createL2ConnectionOshv(connectionIfMap, ifOshMap)) # add vlan objects _vector.addAll(createVlanOshv(vlMap, portOshMap, Framework)) return _vector
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
def disHPUX(hostObj, client, Framework=None, langBund=None): myVec = ObjectStateHolderVector() r = client.execCmd( '/usr/sbin/swlist -a name -a revision -a title -a install_date -a vendor_tag' ) # 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 for line in lines: if ((len(line) < 2) or (line[0] == '#')): continue res = re.search( '([0-9a-zA-Z_.\-\(\),+:/\;=&]+)\s+([0-9a-zA-Z_.\-\(\),+:/\;=]+)\s+([0-9a-zA-Z_.\-\(\),+:/ \;=&\'\#\[\]]+)\s+(\d{8})\d+\.\d+\s+([0-9a-zA-Z_.\-\(\),+:/ \;=&]+)', line) if (res): swName = res.group(1) if swName: myVec.add( hostresource.makeSoftwareOSH2(createHostOSH(hostObj), swName, res.group(5), res.group(2), '', '', '', res.group(4), res.group(3))) return myVec
def DiscoveryMain(Framework): OSHVResult = ObjectStateHolderVector() # # Write implementation to return new result CIs here... ipList = Framework.getTriggerCIDataAsList('PHYSICAL_IP_ADDRESS') portList = Framework.getTriggerCIDataAsList('PHYSICAL_PORT') service_context = Framework.getDestinationAttribute('SERVICE_CONTEXT') service_type = Framework.getDestinationAttribute('SERVICE_TYPE') cluster_id = Framework.getDestinationAttribute('CLUSTER_ID') application_resource_id = Framework.getDestinationAttribute( 'APPLICATION_RESOURCE_ID') cluster_root_class = Framework.getDestinationAttribute('CLUSTER_CLASS') application_resource_class = Framework.getDestinationAttribute( 'APPLICATION_RESOURCE_CLASS') SCPId = Framework.getDestinationAttribute('id') clusterOsh = modeling.createOshByCmdbIdString(cluster_root_class, cluster_id) OSHVResult.addAll( scp.createCPLink(application_resource_id, application_resource_class, cluster_id, cluster_root_class, SCPId, service_context)) for index in range(len(ipList)): scpOsh = scp.createScpOsh(clusterOsh, service_type, ip=ipList[index], port=portList[index], context=service_context) ipOsh = modeling.createIpOSH(ipList[index]) OSHVResult.add(scpOsh) OSHVResult.add(ipOsh) return OSHVResult
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
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
def DiscoveryMain(Framework): OSHVResult = ObjectStateHolderVector() credentialsId = Framework.getDestinationAttribute('credentialsId') ip_address = Framework.getDestinationAttribute('ip_address') url = Framework.getDestinationAttribute('name') version = Framework.getDestinationAttribute('version') query_chunk_size = Framework.getParameter('query_chunk_size') organization = Framework.getParameter('organization') logger.debug('UDDI_Registry started query_chunk_size', query_chunk_size, ' organization:', organization, ' credentialsId', credentialsId) properties = Properties() properties.setProperty(UDDIAgent.CHUNK_SIZE, str(query_chunk_size)) properties.setProperty('ORGANIZATION', str(organization)) properties.setProperty('uddi_version', version) try: uddiAgent = Framework.getAgent(AgentConstants.UDDI_AGENT, ip_address, credentialsId, properties) registryOSH = ObjectStateHolder('uddiregistry') registryOSH.setAttribute('name', url) registryOSH.setAttribute('version', int(version)) OSHVResult.add(registryOSH) logger.debug('Do Uddi Explore url:', url) doUddiExplore(uddiAgent, registryOSH, OSHVResult) except MissingSdkJarException, ex: logger.debugException(ex.getMessage()) Framework.reportError( "UDDI SDK jars are missed. Refer documentation for details")
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
def report(self, ivmHostOsh, hypervisor, vms, reportVmName): if not (ivmHostOsh and hypervisor and vms): raise ValueError( 'Failed to build topology. Not all required entities are discovered.' ) vector = ObjectStateHolderVector() hypervisorOsh = createHypervisorOsh(hypervisor, ivmHostOsh) vector.add(hypervisorOsh) logger.debug(vms) for vm in vms: logger.debug('Report name %s' % reportVmName) if reportVmName and reportVmName.lower().strip() == 'true': virtualServerOsh = createVirtualServerOsh(vm) elif vm.macs: virtualServerOsh = createVirtualServerOsh(vm, False) vector.add(virtualServerOsh) if vm.macs: for mac in vm.macs: vector.add( modeling.createInterfaceOSH(mac, virtualServerOsh)) vector.add( modeling.createLinkOSH("execution_environment", hypervisorOsh, virtualServerOsh)) virtualServerConfigOsh = createVirtualServerConfigOsh( vm.vserver_config, virtualServerOsh) vector.add(virtualServerConfigOsh) return vector
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 reportServerWithDatabases(self, dbServer, container, dependants=None): r""" Report database server with specified container used databases and service end-points @types: db.DatabaseServer, ObjectStateHolder, seq[ObjectStateHolder] -> ObjectStateHolderVector""" if not dbServer: raise ValueError("Database Server is not specified") if not container: raise ValueError("Container for database server is not specified") vector = ObjectStateHolderVector() server_osh = self.reportServer(dbServer, container) vector.add(server_osh) database_oshs = [] for database in dbServer.getDatabases(): database_oshs = list(self.reportDatabase(dbServer, database)) vector.addAll(database_oshs) ipseOsh = None if dbServer.address and dbServer.getPort(): ipseOsh, vector_ = self.reportServerIpServiceEndpoint( dbServer.address, dbServer.getPort(), server_osh, container ) vector.addAll(vector_) for slave in dependants or (): for master in database_oshs or (server_osh,): link = modeling.createLinkOSH("dependency", slave, master) vector.add(link) return server_osh, ipseOsh, database_oshs, list(vector)
def buildDatafiles(self, dataFiles, databaseOsh): oshv = ObjectStateHolderVector() for dataFile in dataFiles: osh = self.buildDataFileOsh(dataFile) osh.setContainer(databaseOsh) oshv.add(osh) return oshv
def reportRemotePeer(remote_peer, localInterfaceOsh, local_mac): vector = ObjectStateHolderVector() if remote_peer.peer_ips: hostOsh = modeling.createHostOSH(str(remote_peer.peer_ips[0])) if remote_peer.platform in VIRTUAL_HOST_PLATFORMS: hostOsh.setBoolAttribute('host_isvirtual', 1) vector.add(hostOsh) for ip in remote_peer.peer_ips: ipOsh = modeling.createIpOSH(ip) linkOsh = modeling.createLinkOSH('containment', hostOsh, ipOsh) vector.add(ipOsh) vector.add(linkOsh) else: hostOsh = ObjectStateHolder('node') hostOsh.setBoolAttribute('host_iscomplete', 1) hostOsh.setStringAttribute('name', remote_peer.system_name) if remote_peer.platform in VIRTUAL_HOST_PLATFORMS: hostOsh.setBoolAttribute('host_isvirtual', 1) vector.add(hostOsh) if remote_peer.interface_name or remote_peer.interface_mac: remoteInterfaceOsh = modeling.createInterfaceOSH(mac = remote_peer.interface_mac, hostOSH = hostOsh, name = remote_peer.interface_name) if not remoteInterfaceOsh: return ObjectStateHolderVector() if remote_peer.interface_name: remoteInterfaceOsh.setStringAttribute('name', remote_peer.interface_name) vector.add(remoteInterfaceOsh) l2id = str(hash(':'.join([remote_peer.interface_mac or remote_peer.interface_name, local_mac]))) vector.addAll(reportLayer2Connection(localInterfaceOsh, remoteInterfaceOsh, l2id)) return vector
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
def osh_createIpOsh(lparOsh, tcpStacks): ipstoexclude = ['127.0.0.1'] # tcpStacks [ip, network, mask, interface name, status, type, mac address]str_name = 'name' str_name = 'name' str_mac_address = 'mac_address' _vector = ObjectStateHolderVector() for mac, tcpentry in tcpStacks.items(): ipAddress = tcpentry[0].strip() if ipAddress not in ipstoexclude: ipOsh = modeling.createIpOSH(ipAddress) probeName = CollectorsParameters.getValue(CollectorsParameters.KEY_COLLECTORS_PROBE_NAME) if isNotNull(probeName): ipOsh.setAttribute('ip_probename', probeName) containedOsh = modeling.createLinkOSH('contained', lparOsh, ipOsh) _vector.add(lparOsh) _vector.add(ipOsh) _vector.add(containedOsh) # create interface ---------------------------------------------------- ifOsh = ObjectStateHolder('interface') interfacename = tcpentry[3].strip() ifOsh.setAttribute(str_name, interfacename) # default the mac address attribute to linkName and update later if MAC found ifOsh.setAttribute(str_mac_address, mac) # if MAC not found for set #linkName as key ifOsh.setContainer(lparOsh) _vector.add(ifOsh) if tcpStacks.has_key(mac): parentLinkOsh = modeling.createLinkOSH('containment', ifOsh, ipOsh) _vector.add(parentLinkOsh) return _vector
def discoverTopology(sapUtils, domain, hostname, connInfo): r'''@types: SapUtils, str, str, ConnectionInfo -> oshv, list[str]''' warnings = [] vector = ObjectStateHolderVector() system_name = getSapSystemName(sapUtils) if system_name: system = sap.System(system_name) isSolMan, tmsDomain, instances = consume(warnings, _discoverIsSolutionManager(sapUtils), _discoverTmsDomain(sapUtils), (_discoverInstances(sapUtils, system.getName()) or ())) # find an instance with ip we are connected to connected_instance = find_instance_with_ip(instances, ip_addr.IPAddress(connInfo.ip)) if connected_instance: logger.info("We have connected to instance %s, adding credentials" % str(connected_instance)) # report currently connected instance system_osh = _reportSystem(sapUtils, system, domain, isSolMan, tmsDomain) connected_osh, additional_vector = sap_abap_discoverer.reportInstanceWithSystem(connected_instance, [ip_addr.IPAddress(connInfo.ip)], system, system_osh, application_ip=ip_addr.IPAddress(connInfo.ip), cred_id=connInfo.credsId) # report all instances vector = second(reportInstances(instances, system, system_osh)) vector.addAll(additional_vector) vector.add(connected_osh) vector.add(system_osh) else: warnings.append('Failed to find destination ip among configured server ips. ' 'No Topology will be reported.') else: warnings.append('Failed to find configured servers. ' 'No Topology will be reported.') return vector, warnings
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
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
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
def DiscoveryMain(Framework): OSHVResult = ObjectStateHolderVector() jobId = Framework.getDiscoveryJobId() host_id = Framework.getDestinationAttribute('id') host_name = Framework.getTriggerCIData('host_name') dnsServers = Framework.getTriggerCIDataAsList('dnsServers') or None try: host_name = host_name.split(" ") ips = pi_utils.getIPs(host_name[0], Framework) if not ips: raise ValueError() hostOSH = modeling.createOshByCmdbIdString('node', host_id) modeling.addHostAttributes(hostOSH, None, host_name[0]) #OSHVResult.add(hostOSH) for ip in ips: ipRes = pi_utils.getIPOSHV(Framework, ip, None, dnsServers, False, True) if ipRes.size() > 0: OSHVResult.add(modeling.createLinkOSH('containment',hostOSH,modeling.createIpOSH(ip))) OSHVResult.addAll(ipRes) if OSHVResult.size() <=0: raise ValueError() except Exception, e: msg = logger.prepareJythonStackTrace("Error getting IPs for %s: " % (host_name), e) errormessages.resolveAndReport(msg, jobId, Framework) logger.error(msg)
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
def doDiscovery(Framework, shell, ip, credentialId, codepage, shellName, warningsList, errorsList, uduid = None): vector = ObjectStateHolderVector() try: try: languageName = shell.osLanguage.bundlePostfix langBund = Framework.getEnvironmentInformation().getBundle('langNetwork', languageName) remoteHostnames = dns_resolver.NsLookupDnsResolver(shell).resolve_hostnames(ip) remoteHostFqdn = None if remoteHostnames: remoteHostFqdn = remoteHostnames[0] shellObj = createShellObj(shell, ip, langBund, languageName, codepage, remoteHostFqdn) try: vector.addAll(discover(shell, shellObj, ip, langBund, Framework, uduid)) finally: # create shell OSH if connection established if shellObj and not vector.size(): hostOsh = modeling.createHostOSH(ip) shellObj.setContainer(hostOsh) vector.add(shellObj) except Exception, ex: strException = ex.getMessage() errormessages.resolveAndAddToObjectsCollections(strException, shellName, warningsList, errorsList) except: msg = str(sys.exc_info()[1]) logger.debugException('') errormessages.resolveAndAddToObjectsCollections(msg, shellName, warningsList, errorsList)
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 buildBackupFiles(self, backupFiles, databaseOsh): oshv = ObjectStateHolderVector() for backupFile in backupFiles: osh = self._buildBackupFileOsh(backupFile) osh.setContainer(databaseOsh) oshv.add(osh) return oshv
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
def disSunOS(hostId, client, Framework=None, langBund=None): ''' Discover physical memory and swap memory on SunOs str, Shell, Framework, Properties -> oshVector @command: /usr/sbin/prtconf @command: swap -l ''' myVec = ObjectStateHolderVector() hostOsh = modeling.createOshByCmdbIdString('host', hostId) output = None try: output = client.execCmd( '/usr/sbin/prtconf', 120000) #V@@CMD_PERMISION tty protocol execution if not output or client.getLastCmdReturnCode() != 0: raise ValueError except: logger.warn("Failed getting memory size from prtconf") else: compiled = re.compile('Memory size: (\d+) Megabytes') matches = compiled.findall(output) totalMemorySizeInMegabytes = 0 for match in matches: totalMemorySizeInMegabytes += int(match) if totalMemorySizeInMegabytes: memory.report(myVec, hostOsh, totalMemorySizeInMegabytes * 1024) # > swap -l #swapfile dev swaplo blocks free #/dev/dsk/c1t0d0s1 32,25 16 1058288 1021616 #/swapfile - 16 7329776 7293968 try: output = client.execAlternateCmds( '/usr/sbin/swap -l', '/etc/swap -l', 'swap -l') #V@@CMD_PERMISION tty protocol execution if not output or client.getLastCmdReturnCode() != 0: raise ValueError except: logger.warn("Failed getting swap size from 'swap'") else: totalSwapSizeInMegabytes = 0 lines = output.split('\n') for line in lines: if line: line = line.strip() if re.search("swapfile\s+dev\s+swaplo\s+blocks\s+free", line): continue matcher = re.match(".*\d+\s+(\d+)\s+\d+$", line) if matcher: swapSizeInMegabytes = int( matcher.group(1)) / 2048 # 1 block = 512 bytes totalSwapSizeInMegabytes += swapSizeInMegabytes if totalSwapSizeInMegabytes: modeling.setHostSwapMemorySizeAttribute(hostOsh, totalSwapSizeInMegabytes) myVec.add(hostOsh) return myVec
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
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
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
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): properties = Properties() vector = ObjectStateHolderVector() properties.setProperty('timeoutDiscover', Framework.getParameter('timeoutDiscover')) properties.setProperty('retryDiscover', Framework.getParameter('retryDiscover')) properties.setProperty('pingProtocol', Framework.getParameter('pingProtocol')) properties.setProperty('threadPoolSize', Framework.getParameter('threadPoolSize')) ip = Framework.getDestinationAttribute('ip_address') domainName = Framework.getDestinationAttribute('domain_name') id = Framework.getTriggerCIData('id') ports = getUDAAvailablePorts(Framework) try: client = Framework.createClient(ClientsConsts.ICMP_PROTOCOL_NAME, properties) try: range_uda_status = {} range_result = pingIPsInRange(Framework, client, ip, ports) range_uda_status.update(range_result) for x in range_uda_status.values(): logger.debug(x) #build the udaStatus context = UdaState.Builder(x.ip).computerName( x.computerName ).alive(x.alive).portAlive(x.portAlive).isDDMI( x.isDDMI).isNative(x.isNative).isWin(x.isWin).osType( x.osType).agentVersion( str(x.agentVersion) + ('-fips' if x.isFIPSEnabled else '')).UDUniqueId( x.UDUniqueId).build() #save UdaStatusService.getInstance().saveUdaStatus(context) if Framework.getParameter('isCreateUDA') == 'true': if x.UDUniqueId: hostOsh = modeling.createHostOSH(x.ip) hostOsh.setStringAttribute( InventoryUtils.ATTR_UD_UNIQUE_ID, x.UDUniqueId) uda = ObjectStateHolder('uda') uda.setStringAttribute('application_ip', x.ip) uda.setStringAttribute('application_ip_domain', domainName) uda.setStringAttribute('discovered_product_name', 'uda') uda.setStringAttribute('version', str(x.agentVersion)) uda.setContainer(hostOsh) vector.add(hostOsh) vector.add(uda) finally: client.close() except: msg = logger.prepareJythonStackTrace('') errormessages.resolveAndReport(msg, ClientsConsts.ICMP_PROTOCOL_NAME, Framework) return vector
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)
def reportInstanceInfo(instInfo, ips, system, credsId=None, connectionClientNr=None, application_ip=None, system_osh=None): r'@types: InstanceInfo, list[ip_addr._BaseIP, System, str, str -> tuple[ObjectStateHolder, ObjectStateHolderVector]' vector = ObjectStateHolderVector() hostReporter = sap.HostReporter(sap.HostBuilder()) ascsReporter = sap_abap.InstanceReporter(sap_abap.AscsInstanceBuilder()) instReporter = sap_abap.InstanceReporter(sap_abap.InstanceBuilder()) # report host of instInfo hostOsh, iVector = hostReporter.reportHostWithIps(*ips) vector.addAll(iVector) # report SAP system if system_osh: system_osh.setStringAttribute( 'data_note', 'This SAP System link to ' + hostOsh.getAttributeValue('host_key')) vector.add(system_osh) # report r3 server on host applicationIp = application_ip isScs = sap_abap.isCentralServicesInstance(instInfo.instance) serverOsh = None if isScs: pdo = sap_abap.AscsInstanceBuilder.createPdo( instInfo.instance, system, homeDirPath=instInfo.homeDirPath, codePage=instInfo.codePage, versionInfo=instInfo.versionInfo, startDate=instInfo.startDate, applicationIp=applicationIp, credId=credsId, connectionClientNr=connectionClientNr) serverOsh = ascsReporter.reportInstance(pdo, hostOsh) else: isCentral = None pdo = sap_abap.InstanceBuilder.createPdo( instInfo.instance, system, homeDirPath=instInfo.homeDirPath, dbLibraryInfo=instInfo.dbLibraryInfo, codePage=instInfo.codePage, numberOfProcesses=instInfo.numberOfProcesses, versionInfo=instInfo.versionInfo, startDate=instInfo.startDate, machineType=instInfo.host.machineType, osInfo=instInfo.host.osInfo, applicationIp=applicationIp, credId=credsId, connectionClientNr=connectionClientNr, isCentral=isCentral) serverOsh = instReporter.reportInstance(pdo, hostOsh) vector.add(serverOsh) return serverOsh, vector
def _report_node_membership(node_osh, cluster_software_osh, red_hat_cluster_osh): vector = ObjectStateHolderVector() member_osh = modeling.createLinkOSH('member', red_hat_cluster_osh, cluster_software_osh) vector.add(member_osh) cluster_software_osh.setContainer(node_osh) return vector
def report(self, hostOsh, process, builder): if process: vector = ObjectStateHolderVector() processOsh = process.build(builder) processOsh.setContainer(hostOsh) vector.add(processOsh) return processOsh, vector raise ValueError("Process is not specified")
def _getResourcesAsVector(resources): vector = ObjectStateHolderVector() for resource in resources: if resource.osh: vector.add(resource.osh) else: logger.warn("OSH was not created for %s" % resource) return vector
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
def report(self, switch, fabricOsh): vector = ObjectStateHolderVector() switchOsh = self.builder.build(switch) vector.add(switchOsh) if fabricOsh: linkOsh = modeling.createLinkOSH('membership', fabricOsh, switchOsh) vector.add(linkOsh) return (switchOsh, vector)