private JasperPrint runAndRender(Report report) throws Exception, JRException { JasperPrint jasperPrint = new JasperPrint(); JasperReport jasperReport = JasperCompileManager.compileReport( System.getProperty("opennms.home") + File.separator + "etc" + File.separator + "report-templates" + File.separator + report.getReportTemplate()); if (report.getReportEngine().equals("jdbc")) { Connection connection = DataSourceFactory.getDataSource().getConnection(); jasperPrint = JasperFillManager.fillReport( jasperReport, paramListToMap(report.getParameterCollection()), connection); connection.close(); } else if (report.getReportEngine().equals("opennms")) { LogUtils.errorf(this, "Sorry the OpenNMS Data source engine is not yet available"); jasperPrint = null; } else { LogUtils.errorf(this, "Unknown report engine: %s ", report.getReportEngine()); jasperPrint = null; } return jasperPrint; }
/** * Method that updates info in List nodes and also save info into database. This method is called * by SnmpCollection after all stuff is done * * @param snmpcoll */ @Transactional public void updateNodeSnmpCollection(final SnmpCollection snmpcoll) { LogUtils.debugf( this, "Updating SNMP collection for %s", InetAddressUtils.str(snmpcoll.getTarget())); LinkableNode node = removeNode(snmpcoll.getTarget()); if (node == null) { LogUtils.errorf( this, "No node found for SNMP collection: %s unscheduling!", snmpcoll.getInfo()); m_scheduler.unschedule(snmpcoll); return; } try { node = m_queryMgr.storeSnmpCollection(node, snmpcoll); } catch (SQLException e) { LogUtils.errorf( this, e, "Failed to save on db snmpcollection/package: %s/%s", snmpcoll.getPackageName(), snmpcoll.getInfo()); return; } if (node != null) { synchronized (m_nodes) { m_nodes.add(node); } } }
/** * {@inheritDoc} * * <p>Initialize the service collector. * * <p>During initialization the JMX collector: - Initializes various configuration factories. - * Verifies access to the database - Verifies access to RRD file repository - Verifies access to * JNI RRD shared library - Determines if JMX to be stored for only the node's primary interface * or for all interfaces. * * @exception RuntimeException Thrown if an unrecoverable error occurs that prevents the plug-in * from functioning. */ @Override public void initialize(Map<String, String> parameters) { // Initialize the JMXDataCollectionConfigFactory try { // XXX was reload(), which isn't test-friendly JMXDataCollectionConfigFactory.init(); } catch (Throwable e) { LogUtils.errorf(this, e, "initialize: Failed to load data collection configuration"); throw new UndeclaredThrowableException(e); } // Make sure we can connect to the database java.sql.Connection ctest = null; try { DataSourceFactory.init(); ctest = DataSourceFactory.getInstance().getConnection(); } catch (final Exception e) { LogUtils.errorf(this, e, "initialize: failed to get a database connection"); throw new UndeclaredThrowableException(e); } finally { if (ctest != null) { try { ctest.close(); } catch (final Throwable t) { LogUtils.debugf( this, "initialize: an exception occured while closing the JDBC connection"); } } } // Save local reference to singleton instance LogUtils.debugf(this, "initialize: successfully instantiated JNI interface to RRD."); }
public void log(String level, String format, Object... args) { if ("TRACE".equals(level)) LogUtils.tracef(this, format, args); if ("DEBUG".equals(level)) LogUtils.debugf(this, format, args); if ("INFO".equals(level)) LogUtils.infof(this, format, args); if ("WARN".equals(level)) LogUtils.warnf(this, format, args); if ("ERROR".equals(level)) LogUtils.errorf(this, format, args); if ("FATAL".equals(level)) LogUtils.errorf(this, format, args); }
/** onInit */ public synchronized void onInit() { Assert.state(m_trapdIpMgr != null, "trapdIpMgr must be set"); Assert.state(m_eventReader != null, "eventReader must be set"); Assert.state(m_backlogQ != null, "backlogQ must be set"); Assert.state(m_snmpTrapAddress != null, "snmpTrapAddress must be set"); Assert.state(m_snmpTrapPort != null, "snmpTrapPort must be set"); Assert.state(m_processor != null, "processor must be set"); try { m_trapdIpMgr.dataSourceSync(); } catch (final SQLException e) { LogUtils.errorf(this, e, "init: Failed to load known IP address list"); throw new UndeclaredThrowableException(e); } try { InetAddress address = getInetAddress(); LogUtils.infof( this, "Listening on %s:%d", address == null ? "[all interfaces]" : InetAddressUtils.str(address), getSnmpTrapPort()); SnmpUtils.registerForTraps(this, this, address, getSnmpTrapPort(), getSnmpV3Users()); m_registeredForTraps = true; LogUtils.debugf(this, "init: Creating the trap session"); } catch (final IOException e) { if (e instanceof java.net.BindException) { managerLog() .error( "init: Failed to listen on SNMP trap port, perhaps something else is already listening?", e); LogUtils.errorf( this, e, "init: Failed to listen on SNMP trap port, perhaps something else is already listening?"); } else { LogUtils.errorf(this, e, "init: Failed to initialize SNMP trap socket"); } throw new UndeclaredThrowableException(e); } try { m_eventReader.open(); } catch (final Throwable e) { LogUtils.errorf(this, e, "init: Failed to open event reader"); throw new UndeclaredThrowableException(e); } }
/** * Check whether the data sources in opennms-datasources.xml are valid. * * @throws MissingDataSourceException A required data source was not found in * opennms-datasources.xml. * @throws InvalidDataSourceException A required data source could not be connected to. */ public void check() throws MissingDataSourceException, InvalidDataSourceException { // First, check to make sure the required datasources are there. boolean dataSourcesFound = true; for (final String dataSource : m_required) { if (!m_dataSources.containsKey(dataSource)) { LogUtils.errorf( this, "Required data source '%s' is missing from opennms-datasources.xml", dataSource); dataSourcesFound = false; } } if (!dataSourcesFound) { throw new MissingDataSourceException( "OpenNMS is missing one or more data sources required for startup."); } // Then, check for the optional ones so we can warn about them going missing. for (final String dataSource : m_optional) { if (!m_dataSources.containsKey(dataSource)) { LogUtils.infof( this, "Data source '%s' is missing from opennms-datasources.xml", dataSource); } } // Finally, try connecting to all data sources, and warn or error as appropriate. for (final JdbcDataSource dataSource : m_dataSources.values()) { final String name = dataSource.getName(); if (!m_required.contains(name) && !m_optional.contains(name)) { LogUtils.warnf(this, "Unknown datasource '%s' was found.", name); } try { Class.forName(dataSource.getClassName()); final Connection connection = DriverManager.getConnection( dataSource.getUrl(), dataSource.getUserName(), dataSource.getPassword()); connection.close(); } catch (final Throwable t) { final String errorMessage = "Unable to connect to data source '%s' at URL '%s' with username '%s', check opennms-datasources.xml and your database permissions."; if (m_required.contains(name)) { LogUtils.errorf(this, errorMessage, name, dataSource.getUrl(), dataSource.getUserName()); throw new InvalidDataSourceException("Data source '" + name + "' failed.", t); } else { LogUtils.warnf(this, errorMessage, name, dataSource.getUrl(), dataSource.getUserName()); } } } }
public boolean scheduleNodeCollection(int nodeid) { LinkableNode node = null; // database changed need reload packageiplist m_linkdConfig.updatePackageIpListMap(); // First of all get Linkable Node LogUtils.debugf(this, "scheduleNodeCollection: Loading node %d from database", nodeid); try { node = m_queryMgr.getSnmpNode(nodeid); if (node == null) { LogUtils.warnf( this, "scheduleNodeCollection: Failed to get linkable node from database with ID %d. Exiting", nodeid); return false; } } catch (final SQLException sqlE) { LogUtils.errorf( this, sqlE, "scheduleNodeCollection: SQL Exception while syncing node object with ID %d with database information.", nodeid); return false; } synchronized (m_nodes) { LogUtils.debugf(this, "adding node %s to the collection", node); m_nodes.add(node); } scheduleCollectionForNode(node); return true; }
/** {@inheritDoc} */ public List<ServiceDetector> getDetectorsForForeignSource(final String foreignSourceName) { final ForeignSource foreignSource = m_foreignSourceRepository.getForeignSource(foreignSourceName); assertNotNull(foreignSource, "Expected a foreignSource with name %s", foreignSourceName); final List<PluginConfig> detectorConfigs = foreignSource.getDetectors(); if (detectorConfigs == null) { return new ArrayList<ServiceDetector>(m_pluginRegistry.getAllPlugins(ServiceDetector.class)); } final List<ServiceDetector> detectors = new ArrayList<ServiceDetector>(detectorConfigs.size()); for (final PluginConfig detectorConfig : detectorConfigs) { final ServiceDetector detector = m_pluginRegistry.getPluginInstance(ServiceDetector.class, detectorConfig); if (detector == null) { errorf(this, "Configured plugin does not exist: %s", detectorConfig); } else { detector.setServiceName(detectorConfig.getName()); detector.init(); detectors.add(detector); } } return detectors; }
public boolean isRequisitioned(OnmsMonitoredService monSvc) { String foreignSource = monSvc.getIpInterface().getNode().getForeignSource(); String foreignId = monSvc.getIpInterface().getNode().getForeignId(); // is this a discovered node if (foreignSource == null) return false; OnmsNode reqNode = getRequisitionedNode(foreignSource, foreignId); if (reqNode == null) { // this is no requisition node? LogUtils.errorf( "No requistion exists for node with foreignSource %s and foreignId %s. Treating node as unrequistioned", foreignSource, foreignId); return false; } OnmsIpInterface reqIp = reqNode.getIpInterfaceByIpAddress(monSvc.getIpAddress()); if (reqIp == null) { // there is no matching requistion ip so the interface was discovered return false; } OnmsMonitoredService reqSvc = reqIp.getMonitoredServiceByServiceType(monSvc.getServiceName()); // if we found the service then its a requistion service return reqSvc != null; }
/** * * * <pre> * The file URL is read and a 'specific IP' is added for each entry * in this file. Each line in the URL file can be one of - * <IP><space>#<comments> * or * <IP> * or * #<comments> * * Lines starting with a '#' are ignored and so are characters after * a '<space>#' in a line. * </pre> * * @param specifics the list to add to * @param url the URL file * @param timeout the timeout for all entries in this URL * @param retries the retries for all entries in this URL * @return a boolean. */ public static boolean addToSpecificsFromURL( final List<IPPollAddress> specifics, final String url, final long timeout, final int retries) { // open the file indicated by the URL InputStream is = null; try { final URL fileURL = new URL(url); is = fileURL.openStream(); // check to see if the file exists if (is == null) { // log something LogUtils.warnf(DiscoveryConfigFactory.class, "URL does not exist: %s", url); return true; } else { return addToSpecificsFromURL(specifics, fileURL.openStream(), timeout, retries); } } catch (final IOException e) { LogUtils.errorf(DiscoveryConfigFactory.class, "Error reading URL: %s", url); return false; } finally { IOUtils.closeQuietly(is); } }
/** onInit */ protected void onInit() { Assert.state(m_queryMgr != null, "must set the queryManager property"); Assert.state(m_linkdConfig != null, "must set the linkdConfig property"); Assert.state(m_scheduler != null, "must set the scheduler property"); Assert.state(m_eventForwarder != null, "must set the eventForwarder property"); // FIXME: circular dependency m_queryMgr.setLinkd(this); m_activepackages = new ArrayList<String>(); // initialize the ipaddrsentevents m_newSuspectEventsIpAddr = new TreeSet<InetAddress>(new InetAddressComparator()); m_newSuspectEventsIpAddr.add(addr("127.0.0.1")); m_newSuspectEventsIpAddr.add(addr("0.0.0.0")); try { m_nodes = m_queryMgr.getSnmpNodeList(); m_queryMgr.updateDeletedNodes(); } catch (SQLException e) { LogUtils.errorf(this, e, "SQL exception executing on database"); throw new UndeclaredThrowableException(e); } Assert.notNull(m_nodes); scheduleCollection(); LogUtils.infof(this, "init: LINKD CONFIGURATION INITIALIZED"); }
private PluginConfiguration[] locatePluginConfigurations() throws Exception { List<PluginConfiguration> pluginConfigs = new LinkedList<PluginConfiguration>(); // first we see if the config is etc exists if (m_configResource != null && m_configResource.isReadable()) { LogUtils.infof(this, "Found Drools Plugin config file %s.", m_configResource); pluginConfigs.add(new PluginConfiguration(m_configResource)); } // then we look in each plugin dir for a config File[] pluginDirs = getPluginDirs(); for (File pluginDir : pluginDirs) { File configFile = new File(pluginDir, PLUGIN_CONFIG_FILE_NAME); if (!configFile.exists()) { LogUtils.errorf( this, "Drools Plugin directory %s does not contains a %s config file. Ignoring plugin.", pluginDir, PLUGIN_CONFIG_FILE_NAME); } else { LogUtils.infof( this, "Found Drools Plugin directory %s containing a %s config file.", pluginDir, PLUGIN_CONFIG_FILE_NAME); pluginConfigs.add(new PluginConfiguration(new FileSystemResource(configFile))); } } return pluginConfigs.toArray(new PluginConfiguration[0]); }
/* (non-Javadoc) * @see org.opennms.features.vaadin.mibcompiler.api.MibParser#getPrefabGraphs() */ @Override public List<PrefabGraph> getPrefabGraphs() { if (module == null) { return null; } List<PrefabGraph> graphs = new ArrayList<PrefabGraph>(); LogUtils.infof(this, "Generating graph templates for %s", module.getId()); NameCutter cutter = new NameCutter(); try { for (SmiVariable v : module.getVariables()) { String groupName = getGroupName(v); String resourceType = getResourceType(v); if (resourceType == null) resourceType = "nodeSnmp"; String typeName = getMetricType(v.getType().getPrimitiveType()); if (v.getId().contains("Index")) { // Treat SNMP Indexes as strings. typeName = "string"; } int order = 1; if (typeName != null && !typeName.toLowerCase().contains("string")) { String name = groupName + '.' + v.getId(); String alias = cutter.trimByCamelCase(v.getId(), 19); // RRDtool/JRobin DS size restriction. String descr = v.getDescription().replaceAll("[\n\r]", "").replaceAll("\\s+", " "); StringBuffer sb = new StringBuffer(); sb.append("--title=\"").append(v.getId()).append("\" \\\n"); sb.append(" DEF:var={rrd1}:").append(alias).append(":AVERAGE \\\n"); sb.append(" LINE1:var#0000ff:\"").append(v.getId()).append("\" \\\n"); sb.append(" GPRINT:var:AVERAGE:\"Avg\\\\: %8.2lf %s\" \\\n"); sb.append(" GPRINT:var:MIN:\"Min\\\\: %8.2lf %s\" \\\n"); sb.append(" GPRINT:var:MAX:\"Max\\\\: %8.2lf %s\\n\""); sb.append("\n\n"); PrefabGraph graph = new PrefabGraph( name, descr, new String[] {alias}, sb.toString(), new String[0], new String[0], order++, new String[] {resourceType}, descr, null, null, new String[0]); graphs.add(graph); } } } catch (Throwable e) { String errors = e.getMessage(); if (errors == null || errors.trim().equals("")) errors = "An unknown error accured when generating graph templates from the MIB " + module.getId(); LogUtils.errorf(this, e, "Graph templates parsing error: %s", errors); errorHandler.addError(errors); return null; } return graphs; }
/** * {@inheritDoc} * * @throws ReportRunException */ public synchronized String runReport(Report report, String reportDirectory) throws ReportRunException { String outputFile = null; try { outputFile = generateReportName(reportDirectory, report.getReportName(), report.getReportFormat()); JasperPrint print = runAndRender(report); outputFile = saveReport(print, report.getReportFormat(), outputFile); } catch (JRException e) { LogUtils.errorf(this, e, "Error running report: %s", e.getMessage()); throw new ReportRunException("Caught JRException: " + e.getMessage()); } catch (Throwable e) { LogUtils.errorf(this, e, "Unexpected exception: %s", e.getMessage()); throw new ReportRunException( "Caught unexpected " + e.getClass().getName() + ": " + e.getMessage()); } return outputFile; }
/** * Method that uses info in hash snmpprimaryip2nodes and also save info into database. This method * is called by DiscoveryLink after all stuff is done * * @param discover */ void updateDiscoveryLinkCollection(final DiscoveryLink discover) { try { m_queryMgr.storeDiscoveryLink(discover); } catch (SQLException e) { LogUtils.errorf( this, e, "Failed to save discoverylink on database for package: %s", discover.getPackageName()); } }
public SnmpCollection createCollection(int nodeid, final InetAddress ipaddr) { SnmpCollection coll = null; try { coll = new SnmpCollection(this, nodeid, SnmpPeerFactory.getInstance().getAgentConfig(ipaddr)); } catch (final Throwable t) { LogUtils.errorf( this, t, "getSnmpCollection: Failed to load snmpcollection parameter from SNMP configuration file"); } return coll; }
@Transactional(readOnly = true) private OnmsNode findNodebyNodeLabel(final String label) { Collection<OnmsNode> nodes = m_nodeDao.findByLabel(label); if (nodes.size() == 1) { return nodes.iterator().next(); } errorf( this, "Unable to locate a unique node using label %s: %d nodes found. Ignoring relationship.", label, nodes.size()); return null; }
/* (non-Javadoc) * @see org.opennms.features.vaadin.mibcompiler.MibParser#parseMib(java.io.File) */ public boolean parseMib(File mibFile) { // Validate MIB Directory if (mibDirectory == null) { errorHandler.addError("MIB directory has not been set."); return false; } // Reset error handler and dependencies tracker missingDependencies.clear(); // Set UP the MIB Queue MIB to be parsed List<URL> queue = new ArrayList<URL>(); parser.getFileParserPhase().setInputUrls(queue); // Create a cache of filenames to do case-insensitive lookups final Map<String, File> mibDirectoryFiles = new HashMap<String, File>(); for (final File file : mibDirectory.listFiles()) { mibDirectoryFiles.put(file.getName().toLowerCase(), file); } // Parse MIB LogUtils.debugf(this, "Parsing %s", mibFile.getAbsolutePath()); SmiMib mib = null; addFileToQueue(queue, mibFile); while (true) { errorHandler.reset(); try { mib = parser.parse(); } catch (Exception e) { LogUtils.errorf(this, e, "Can't compile %s", mibFile); errorHandler.addError(e.getMessage()); return false; } if (errorHandler.isOk()) { break; } else { List<String> dependencies = errorHandler.getDependencies(); if (dependencies.isEmpty()) // No dependencies, everything is fine. break; missingDependencies.addAll(dependencies); if (!addDependencyToQueue(queue, mibDirectoryFiles)) break; } } if (errorHandler.isNotOk()) // There are still non-dependency related problems. return false; // Extracting the module from compiled MIB. LogUtils.infof(this, "The MIB %s has been parsed successfully.", mibFile.getAbsolutePath()); module = getModule(mib, mibFile); return module != null; }
/** * Initializes the expansion regular expression. The exception is going to be thrown away if the * RE can't be compiled, thus the compilation should be tested prior to runtime. */ static { try { m_expandRE = new RE(NOTIFD_EXPANSION_PARM); } catch (RESyntaxException e) { // this shouldn't throw an exception, should be tested prior to // runtime LogUtils.errorf( NotificationManager.class, e, "failed to compile RE %s", NOTIFD_EXPANSION_PARM); // FIXME: wrap this in runtime exception since SOMETIMES we are using // an incorrect version of regexp pulled from xalan that is doesn't // extend RuntimeException only Exception. We really need to fix that. // See Bug# 1736 in Bugzilla. throw new RuntimeException(e); } }
/** * addToSpecificsFromURL * * @param specifics a {@link java.util.List} object. * @param is a {@link java.io.InputStream} object. * @param timeout a long. * @param retries a int. * @return a boolean. * @throws java.io.IOException if any. */ public static boolean addToSpecificsFromURL( final List<IPPollAddress> specifics, final InputStream is, final long timeout, final int retries) throws IOException { boolean bRet = true; try { final BufferedReader buffer = new BufferedReader(new InputStreamReader(is, "UTF-8")); String ipLine = null; String specIP = null; // get each line of the file and turn it into a specific range while ((ipLine = buffer.readLine()) != null) { ipLine = ipLine.trim(); if (ipLine.length() == 0 || ipLine.charAt(0) == DiscoveryConfigFactory.COMMENT_CHAR) { // blank line or skip comment continue; } // check for comments after IP final int comIndex = ipLine.indexOf(DiscoveryConfigFactory.COMMENT_STR); if (comIndex == -1) { specIP = ipLine; } else { specIP = ipLine.substring(0, comIndex); specIP = specIP.trim(); } try { specifics.add(new IPPollAddress(specIP, timeout, retries)); } catch (final UnknownHostException e) { LogUtils.warnf( DiscoveryConfigFactory.class, "Unknown host \'%s\' inside discovery include file: address ignored", specIP); } specIP = null; } } catch (final UnsupportedEncodingException e) { LogUtils.errorf(DiscoveryConfigFactory.class, "Your JVM doesn't support UTF-8"); return false; } return bRet; }
public boolean isRequisitioned(OnmsNode node) { String foreignSource = node.getForeignSource(); String foreignId = node.getForeignId(); // is this a discovered node if (foreignSource == null) return false; OnmsNode reqNode = getRequisitionedNode(foreignSource, foreignId); if (reqNode == null) { // this is no requisition node? LogUtils.errorf( "No requistion exists for node with foreignSource %s and foreignId %s. Treating node as unrequistioned", foreignSource, foreignId); return false; } else { return true; } }
/** * Update database when an interface is deleted * * @param nodeid the nodeid for the node * @param ipAddr the ip address of the interface * @param ifIndex the ifIndex of the interface */ void deleteInterface(int nodeid, String ipAddr, int ifIndex) { LogUtils.debugf( this, "deleteInterface: marking table entries as deleted for node %d with IP address %s and ifIndex %s", nodeid, ipAddr, (ifIndex > -1 ? "" + ifIndex : "N/A")); try { m_queryMgr.updateForInterface(nodeid, ipAddr, ifIndex, QueryManager.ACTION_DELETE); } catch (SQLException sqlE) { LogUtils.errorf(this, sqlE, "deleteInterface: SQL Exception while updating database."); } // database changed need reload packageiplist m_linkdConfig.updatePackageIpListMap(); }
/* (non-Javadoc) * @see org.opennms.features.vaadin.mibcompiler.api.MibParser#getDataCollection() */ public DatacollectionGroup getDataCollection() { if (module == null) { return null; } LogUtils.infof(this, "Generating data collection configuration for %s", module.getId()); DatacollectionGroup dcGroup = new DatacollectionGroup(); dcGroup.setName(module.getId()); NameCutter cutter = new NameCutter(); try { for (SmiVariable v : module.getVariables()) { String groupName = getGroupName(v); String resourceType = getResourceType(v); Group group = getGroup(dcGroup, groupName, resourceType); String typeName = getMetricType(v.getType().getPrimitiveType()); if (typeName != null) { String alias = cutter.trimByCamelCase(v.getId(), 19); // RRDtool/JRobin DS size restriction. MibObj mibObj = new MibObj(); mibObj.setOid('.' + v.getOidStr()); mibObj.setInstance(resourceType == null ? "0" : resourceType); mibObj.setAlias(alias); mibObj.setType(typeName); group.addMibObj(mibObj); if (typeName.equals("string") && resourceType != null) { for (ResourceType rs : dcGroup.getResourceTypeCollection()) { if (rs.getName().equals(resourceType) && rs.getResourceLabel().equals("${index}")) { rs.setResourceLabel("${" + v.getId() + "} (${index})"); } } } } } } catch (Throwable e) { String errors = e.getMessage(); if (errors == null || errors.trim().equals("")) errors = "An unknown error accured when generating data collection objects from the MIB " + module.getId(); LogUtils.errorf(this, e, "Data Collection parsing error: %s", errors); errorHandler.addError(errors); return null; } return dcGroup; }
/* (non-Javadoc) * @see org.opennms.features.vaadin.mibcompiler.services.MibParser#getEvents(java.lang.String) */ public Events getEvents(String ueibase) { if (module == null) { return null; } LogUtils.infof( this, "Generating events for %s using the following UEI Base: %s", module.getId(), ueibase); try { return convertMibToEvents(module, ueibase); } catch (Throwable e) { String errors = e.getMessage(); if (errors == null || errors.trim().equals("")) errors = "An unknown error accured when generating events objects from the MIB " + module.getId(); LogUtils.errorf(this, e, "Event parsing error: %s", errors); errorHandler.addError(errors); return null; } }
public boolean isRequisitioned(OnmsIpInterface ip) { String foreignSource = ip.getNode().getForeignSource(); String foreignId = ip.getNode().getForeignId(); // is this a discovered node if (foreignSource == null) return false; OnmsNode reqNode = getRequisitionedNode(foreignSource, foreignId); if (reqNode == null) { // this is no requisition node? LogUtils.errorf( "No requistion exists for node with foreignSource %s and foreignId %s. Treating node as unrequistioned", foreignSource, foreignId); return false; } OnmsIpInterface reqIp = reqNode.getIpInterfaceByIpAddress(ip.getIpAddress()); // if we found the ip then its a requisitioned interface return reqIp != null; }
void suspendNodeCollection(int nodeid) { LogUtils.debugf( this, "suspendNodeCollection: suspend collection LinkableNode for node %d", nodeid); try { m_queryMgr.update(nodeid, QueryManager.ACTION_UPTODATE); } catch (SQLException sqlE) { LogUtils.errorf( this, sqlE, "suspendNodeCollection: SQL Exception while syncing node object with database information."); } LinkableNode node = getNode(nodeid); if (node == null) { LogUtils.warnf(this, "suspendNodeCollection: found null ReadyRunnable"); } else { // get collections // get readyRunnuble // suspend RR Collection<SnmpCollection> collections = getSnmpCollections(nodeid, node.getSnmpPrimaryIpAddr(), node.getSysoid()); LogUtils.debugf( this, "suspendNodeCollection: fetched SnmpCollections from scratch, iterating over %d objects to wake them up", collections.size()); for (SnmpCollection collection : collections) { ReadyRunnable rr = getReadyRunnable(collection); if (rr == null) { LogUtils.warnf(this, "suspendNodeCollection: suspend: node not found: %d", nodeid); return; } else { rr.suspend(); } } } }
void deleteNode(int nodeid) { LogUtils.debugf(this, "deleteNode: deleting LinkableNode for node %s", nodeid); try { m_queryMgr.update(nodeid, QueryManager.ACTION_DELETE); } catch (SQLException sqlE) { LogUtils.errorf( this, sqlE, "deleteNode: SQL Exception while syncing node object with database information."); } LinkableNode node = removeNode(nodeid); if (node == null) { LogUtils.warnf(this, "deleteNode: node not found: %d", nodeid); } else { Collection<SnmpCollection> collections = getSnmpCollections(nodeid, node.getSnmpPrimaryIpAddr(), node.getSysoid()); LogUtils.debugf( this, "deleteNode: fetched SnmpCollections from scratch, iterating over %d objects to wake them up", collections.size()); for (SnmpCollection collection : collections) { ReadyRunnable rr = getReadyRunnable(collection); if (rr == null) { LogUtils.warnf(this, "deleteNode: found null ReadyRunnable"); return; } else { rr.unschedule(); } } } // database changed need reload packageiplist m_linkdConfig.updatePackageIpListMap(); }
/** * {@inheritDoc} * * <p>Perform data collection. */ @Override public CollectionSet collect(CollectionAgent agent, EventProxy eproxy, Map<String, Object> map) { InetAddress ipaddr = agent.getAddress(); JMXNodeInfo nodeInfo = agent.getAttribute(NODE_INFO_KEY); Map<String, BeanInfo> mbeans = nodeInfo.getMBeans(); String collDir = serviceName; boolean useMbeanForRrds = ParameterMap.getKeyedBoolean(map, "use-mbean-name-for-rrds", false); String port = ParameterMap.getKeyedString(map, "port", null); String friendlyName = ParameterMap.getKeyedString(map, "friendly-name", port); if (useFriendlyName) { collDir = friendlyName; } JMXCollectionSet collectionSet = new JMXCollectionSet(agent, collDir); collectionSet.setCollectionTimestamp(new Date()); JMXCollectionResource collectionResource = collectionSet.getResource(); ConnectionWrapper connection = null; LogUtils.debugf( this, "collecting %s on node ID %d", InetAddressUtils.str(ipaddr), nodeInfo.getNodeId()); try { connection = getMBeanServerConnection(map, ipaddr); if (connection == null) { return collectionSet; } MBeanServerConnection mbeanServer = connection.getMBeanServer(); int retry = ParameterMap.getKeyedInteger(map, "retry", 3); for (int attempts = 0; attempts <= retry; attempts++) { try { /* * Iterate over the mbeans, for each object name perform a * getAttributes, the update the RRD. */ for (Iterator<BeanInfo> iter = mbeans.values().iterator(); iter.hasNext(); ) { BeanInfo beanInfo = iter.next(); String mbeanName = beanInfo.getMbeanName(); String objectName = beanInfo.getObjectName(); String excludeList = beanInfo.getExcludes(); // All JMX collected values are per node String obj = useMbeanForRrds ? mbeanName : objectName; AttributeGroupType attribGroupType = new AttributeGroupType(fixGroupName(obj), "all"); List<String> attribNames = beanInfo.getAttributeNames(); List<String> compAttribNames = beanInfo.getCompositeAttributeNames(); for (String compAttribName : compAttribNames) { if (attribNames.contains(compAttribName)) { attribNames.remove(compAttribName); String[] ac = compAttribName.split("\\|", -1); String attrName = ac[0]; if (!attribNames.contains(attrName)) { attribNames.add(attrName); } } } // log.debug(" JMXCollector: processed the following attributes: " + // attribNames.toString()); // log.debug(" JMXCollector: processed the following Composite Attributes: " + // compAttribNames.toString()); String[] attrNames = attribNames.toArray(new String[attribNames.size()]); if (objectName.indexOf("*") == -1) { LogUtils.debugf( this, "%s Collector - getAttributes: %s, # attributes: %d, # composite attribute members: %d", serviceName, objectName, attrNames.length, compAttribNames.size()); try { ObjectName oName = new ObjectName(objectName); if (mbeanServer.isRegistered(oName)) { AttributeList attrList = mbeanServer.getAttributes(oName, attrNames); Map<String, JMXDataSource> dsMap = nodeInfo.getDsMap(); for (Object attribute : attrList) { List<String> compositeMemberKeys = new ArrayList<String>(); Boolean isComposite = false; Attribute attrib = (Attribute) attribute; for (String compAttrName : compAttribNames) { String[] attribKeys = compAttrName.split("\\|", -1); if (attrib.getName().equals(attribKeys[0])) { compositeMemberKeys.add(attribKeys[1]); isComposite = true; } } if (isComposite) { try { CompositeData cd = (CompositeData) attrib.getValue(); for (String key : compositeMemberKeys) { /* value = cd.get(key); log.debug(" JMXCollector - got CompositeData: " + objectName + "|" + attrib.getName() + "|" + key + " |-> " + cd.get(key).toString()); */ JMXDataSource ds = dsMap.get(objectName + "|" + attrib.getName() + "|" + key); JMXCollectionAttributeType attribType = new JMXCollectionAttributeType(ds, null, null, attribGroupType); collectionResource.setAttributeValue(attribType, cd.get(key).toString()); } } catch (final ClassCastException cce) { LogUtils.debugf( this, cce, "%s Collection - getAttributes (try CompositeData) - ERROR: Failed to cast attribute value to type CompositeData!", serviceName); } } else { // this is a normal attribute, so fallback to default handler JMXDataSource ds = dsMap.get(objectName + "|" + attrib.getName()); JMXCollectionAttributeType attribType = new JMXCollectionAttributeType(ds, null, null, attribGroupType); collectionResource.setAttributeValue( attribType, attrib.getValue().toString()); } } } } catch (final InstanceNotFoundException e) { LogUtils.errorf(this, e, "Unable to retrieve attributes from %s", objectName); } } else { /* * This section is for ObjectNames that use the * '*' wildcard */ Set<ObjectName> mbeanSet = getObjectNames(mbeanServer, objectName); for (Iterator<ObjectName> objectNameIter = mbeanSet.iterator(); objectNameIter.hasNext(); ) { ObjectName oName = objectNameIter.next(); LogUtils.debugf( this, "%s Collector - getAttributesWC: %s, # attributes: %d, alias: %s", serviceName, oName, attrNames.length, beanInfo.getKeyAlias()); try { if (excludeList == null) { // the exclude list doesn't apply if (mbeanServer.isRegistered(oName)) { AttributeList attrList = mbeanServer.getAttributes(oName, attrNames); Map<String, JMXDataSource> dsMap = nodeInfo.getDsMap(); for (Object attribute : attrList) { Attribute attrib = (Attribute) attribute; JMXDataSource ds = dsMap.get(objectName + "|" + attrib.getName()); JMXCollectionAttributeType attribType = new JMXCollectionAttributeType( ds, oName.getKeyProperty(beanInfo.getKeyField()), beanInfo.getKeyAlias(), attribGroupType); collectionResource.setAttributeValue( attribType, attrib.getValue().toString()); } } } else { /* * filter out calls if the key field * matches an entry in the exclude * list */ String keyName = oName.getKeyProperty(beanInfo.getKeyField()); boolean found = false; StringTokenizer st = new StringTokenizer(excludeList, ","); while (st.hasMoreTokens()) { if (keyName.equals(st.nextToken())) { found = true; break; } } if (!found) { if (mbeanServer.isRegistered(oName)) { AttributeList attrList = mbeanServer.getAttributes(oName, attrNames); Map<String, JMXDataSource> dsMap = nodeInfo.getDsMap(); for (Object attribute : attrList) { Attribute attrib = (Attribute) attribute; JMXDataSource ds = dsMap.get(objectName + "|" + attrib.getName()); JMXCollectionAttributeType attribType = new JMXCollectionAttributeType( ds, oName.getKeyProperty(beanInfo.getKeyField()), beanInfo.getKeyAlias(), attribGroupType); collectionResource.setAttributeValue( attribType, attrib.getValue().toString()); } } } } } catch (final InstanceNotFoundException e) { LogUtils.errorf(this, e, "Error retrieving attributes for %s", oName); } } } } break; } catch (final Exception e) { LogUtils.debugf( this, e, "%s Collector.collect: IOException while collecting address: %s", serviceName, agent.getAddress()); } } } catch (final Exception e) { LogUtils.errorf(this, e, "Error getting MBeanServer"); } finally { if (connection != null) { connection.close(); } } collectionSet.setStatus(ServiceCollector.COLLECTION_SUCCEEDED); return collectionSet; }
/** * {@inheritDoc} * * <p>Poll an {@link InetAddress} for SSH availability. * * <p>During the poll an attempt is made to connect on the specified port. If the connection * request is successful, the banner line generated by the interface is parsed and if the banner * text indicates that we are talking to Provided that the interface's response is valid we mark * the poll status as available and return. */ public PollStatus poll(InetAddress address, Map<String, Object> parameters) { TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT); int port = ParameterMap.getKeyedInteger(parameters, "port", DEFAULT_PORT); String banner = ParameterMap.getKeyedString(parameters, "banner", null); String match = ParameterMap.getKeyedString(parameters, "match", null); String clientBanner = ParameterMap.getKeyedString(parameters, "client-banner", Ssh.DEFAULT_CLIENT_BANNER); PollStatus ps = PollStatus.unavailable(); Ssh ssh = new Ssh(address, port, tracker.getConnectionTimeout()); ssh.setClientBanner(clientBanner); RE regex = null; try { if (match == null && (banner == null || banner.equals("*"))) { regex = null; } else if (match != null) { regex = new RE(match); } else if (banner != null) { regex = new RE(banner); } } catch (final RESyntaxException e) { final String matchString = match == null ? banner : match; LogUtils.infof( this, "Invalid regular expression for SSH banner match /%s/: %s", matchString, e.getMessage()); LogUtils.debugf(this, e, "Invalid Regular expression for SSH banner match /%s/", matchString); } for (tracker.reset(); tracker.shouldRetry() && !ps.isAvailable(); tracker.nextAttempt()) { try { ps = ssh.poll(tracker); } catch (final InsufficientParametersException e) { LogUtils.errorf(this, e, "An error occurred polling host '%s'", address); break; } if (!ps.isAvailable()) { // not able to connect, retry continue; } // If banner matching string is null or wildcard ("*") then we // only need to test connectivity and we've got that! if (regex == null) { return ps; } else { String response = ssh.getServerBanner(); if (response == null) { return PollStatus.unavailable("server closed connection before banner was received."); } if (regex.match(response)) { LogUtils.debugf(this, "isServer: matching response=%s", response); return ps; } else { // Got a response but it didn't match... no need to attempt // retries LogUtils.debugf(this, "isServer: NON-matching response=%s", response); return PollStatus.unavailable( "server responded, but banner did not match '" + banner + "'"); } } } return ps; }
private String saveReport(JasperPrint jasperPrint, String format, String destFileName) throws JRException, Exception { String reportName = null; switch (Format.valueOf(format)) { case pdf: JasperExportManager.exportReportToPdfFile(jasperPrint, destFileName); reportName = destFileName; break; case html: JasperExportManager.exportReportToHtmlFile(jasperPrint, destFileName); reportName = createZip(destFileName); break; case xml: JasperExportManager.exportReportToXmlFile(jasperPrint, destFileName, true); reportName = createZip(destFileName); break; case csv: JRCsvExporter exporter = new JRCsvExporter(); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, destFileName); exporter.exportReport(); reportName = destFileName; break; default: LogUtils.errorf(this, "Error Running Report: Unknown Format: %s", format); } return reportName; }