/** * 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); } } }
void wakeUpNodeCollection(int nodeid) { LinkableNode node = getNode(nodeid); if (node == null) { LogUtils.warnf( this, "wakeUpNodeCollection: node not found during scheduling with ID %d", nodeid); scheduleNodeCollection(nodeid); } else { // get collections // get readyRunnuble // wakeup RR Collection<SnmpCollection> collections = getSnmpCollections(nodeid, node.getSnmpPrimaryIpAddr(), node.getSysoid()); LogUtils.debugf( this, "wakeUpNodeCollection: 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, "wakeUpNodeCollection: found null ReadyRunnable"); return; } else { rr.wakeUp(); } } } }
/** * Adds the dependency to the queue. * * @param queue the queue * @param mibDirectoryFiles * @return true, if successful */ private boolean addDependencyToQueue( final List<URL> queue, final Map<String, File> mibDirectoryFiles) { final List<String> dependencies = new ArrayList<String>(missingDependencies); boolean ok = true; for (String dependency : dependencies) { boolean found = false; for (String suffix : MIB_SUFFIXES) { final String fileName = (dependency + suffix).toLowerCase(); if (mibDirectoryFiles.containsKey(fileName)) { File f = mibDirectoryFiles.get(fileName); LogUtils.debugf(this, "Checking dependency file %s", f.getAbsolutePath()); if (f.exists()) { LogUtils.infof(this, "Adding dependency file %s", f.getAbsolutePath()); addFileToQueue(queue, f); missingDependencies.remove(dependency); found = true; break; } } LogUtils.debugf(this, "Dependency file %s doesn't exist", fileName); } if (!found) { LogUtils.warnf(this, "Couldn't find dependency %s on %s", dependency, mibDirectory); ok = false; } } return ok; }
/** * Send a newSuspect event for the interface construct event with 'linkd' as source * * @param ipInterface The interface for which the newSuspect event is to be generated * @param ipowner The host that hold this ipInterface information * @pkgName The package Name of the ready runnable involved */ void sendNewSuspectEvent(InetAddress ipaddress, InetAddress ipowner, String pkgName) { if (m_newSuspectEventsIpAddr.contains(ipaddress)) { LogUtils.infof( this, "sendNewSuspectEvent: nothing to send, suspect event previously sent for IP address: %s", str(ipaddress)); return; } else if (!isInterfaceInPackageRange(ipaddress, pkgName)) { LogUtils.infof( this, "sendNewSuspectEvent: nothing to send for IP address: %s, not in package: %s", str(ipaddress), pkgName); return; } org.opennms.netmgt.config.linkd.Package pkg = m_linkdConfig.getPackage(pkgName); boolean autodiscovery = false; if (pkg.hasAutoDiscovery()) autodiscovery = pkg.getAutoDiscovery(); else autodiscovery = m_linkdConfig.isAutoDiscoveryEnabled(); if (autodiscovery) { EventBuilder bldr = new EventBuilder(EventConstants.NEW_SUSPECT_INTERFACE_EVENT_UEI, "linkd"); bldr.setHost(str(ipowner)); bldr.setInterface(ipaddress); m_eventForwarder.sendNow(bldr.getEvent()); m_newSuspectEventsIpAddr.add(ipaddress); } }
/* (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; }
/** 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"); }
/** * * * <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); } }
/** * Parse the {@link DataAccessException} to see if special problems were encountered while * performing the query. See issue NMS-5029 for examples of stack traces that can be thrown from * these calls. {@see http://issues.opennms.org/browse/NMS-5029} */ private void logExtraSaveOrUpdateExceptionInformation( final T entity, final DataAccessException e) { Throwable cause = e; while (cause.getCause() != null) { // if (cause.getCause().getClass().getName().equals(PSQLException.class.getName())) { if (cause.getMessage().contains("duplicate key value violates unique constraint")) { final ClassMetadata meta = getSessionFactory().getClassMetadata(m_entityClass); LogUtils.warnf( this, "Duplicate key constraint violation, class: %s, key value: %s", m_entityClass.getName(), meta.getPropertyValue(entity, meta.getIdentifierPropertyName(), EntityMode.POJO)); break; } else if (cause.getMessage().contains("given object has a null identifier")) { LogUtils.warnf( this, "Null identifier on object, class: %s: %s", m_entityClass.getName(), entity.toString()); break; } // } cause = cause.getCause(); } }
/** * {@inheritDoc} * * <p>Responsible for performing all necessary initialization for the specified interface in * preparation for data collection. */ @Override public void initialize(CollectionAgent agent, Map<String, Object> parameters) { InetAddress ipAddr = agent.getAddress(); int nodeID = agent.getNodeId(); // Retrieve the name of the JMX data collector String collectionName = ParameterMap.getKeyedString(parameters, "collection", serviceName); final String hostAddress = InetAddressUtils.str(ipAddr); LogUtils.debugf( this, "initialize: InetAddress=%s, collectionName=%s", hostAddress, collectionName); JMXNodeInfo nodeInfo = new JMXNodeInfo(nodeID); LogUtils.debugf(this, "nodeInfo: %s %d %s", hostAddress, nodeID, agent); /* * Retrieve list of MBean objects to be collected from the * remote agent which are to be stored in the node-level RRD file. * These objects pertain to the node itself not any individual * interfaces. */ Map<String, List<Attrib>> attrMap = JMXDataCollectionConfigFactory.getInstance() .getAttributeMap(collectionName, serviceName, hostAddress); nodeInfo.setAttributeMap(attrMap); Map<String, JMXDataSource> dsList = buildDataSourceList(collectionName, attrMap); nodeInfo.setDsMap(dsList); nodeInfo.setMBeans(JMXDataCollectionConfigFactory.getInstance().getMBeanInfo(collectionName)); // Add the JMXNodeInfo object as an attribute of the interface agent.setAttribute(NODE_INFO_KEY, nodeInfo); agent.setAttribute("collectionName", collectionName); }
public synchronized void sendNow(final Event event) { // Expand the event parms final EventExpander expander = new EventExpander(); expander.setEventConfDao(new EmptyEventConfDao()); expander.expandEvent(event); m_pendingEvents++; LogUtils.debugf(this, "StartEvent processing (%d remaining)", m_pendingEvents); LogUtils.debugf(this, "Received: ", new EventWrapper(event)); m_anticipator.eventReceived(event); final Runnable r = new Runnable() { public void run() { try { m_eventWriter.writeEvent(event); broadcastNow(event); m_anticipator.eventProcessed(event); } finally { synchronized (MockEventIpcManager.this) { m_pendingEvents--; LogUtils.debugf(this, "Finished processing event (%d remaining)", m_pendingEvents); MockEventIpcManager.this.notifyAll(); } } } }; if (isSynchronous()) { r.run(); } else { getScheduler().schedule(r, m_eventDelay, TimeUnit.MILLISECONDS); } }
/** * {@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."); }
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; }
/** {@inheritDoc} */ @Transactional public OnmsIpInterface setIsPrimaryFlag(final Integer nodeId, final String ipAddress) { // TODO upsert? not sure if this needs one.. leave the todo here in case if (nodeId == null) { LogUtils.debugf(this, "nodeId is null!"); return null; } else if (ipAddress == null) { LogUtils.debugf(this, "ipAddress is null!"); return null; } final OnmsIpInterface svcIface = m_ipInterfaceDao.findByNodeIdAndIpAddress(nodeId, ipAddress); if (svcIface == null) { LogUtils.infof( this, "unable to find IPInterface for nodeId=%s, ipAddress=%s", nodeId, ipAddress); return null; } OnmsIpInterface primaryIface = null; if (svcIface.isPrimary()) { primaryIface = svcIface; } else if (svcIface.getNode().getPrimaryInterface() == null) { svcIface.setIsSnmpPrimary(PrimaryType.PRIMARY); m_ipInterfaceDao.saveOrUpdate(svcIface); m_ipInterfaceDao.flush(); primaryIface = svcIface; } else { svcIface.setIsSnmpPrimary(PrimaryType.SECONDARY); m_ipInterfaceDao.saveOrUpdate(svcIface); m_ipInterfaceDao.flush(); } m_ipInterfaceDao.initialize(primaryIface); return primaryIface; }
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; }
@Override @Transactional public void deleteComponent( final String type, final String foreignSource, final String foreignId, final boolean deleteOrphans) { LogUtils.debugf( this, "deleteSubcomponent(%s, %s, %s, %s)", type, foreignSource, foreignId, Boolean.valueOf(deleteOrphans)); final NCSComponent component = getComponent(type, foreignSource, foreignId); final ComponentIdentifier id = getIdentifier(component); final ComponentEventQueue ceq = new ComponentEventQueue(); deleteComponent(id, ceq, deleteOrphans); try { ceq.sendAll(m_eventProxy); } catch (final EventProxyException e) { LogUtils.warnf( this, e, "Component %s deleted, but an error occured while sending delete/update events.", id); } }
/** * This method schedules a {@link SnmpCollection} for node for each package. Also schedule * discovery link on package when not still activated. * * @param node */ private void scheduleCollectionForNode(final LinkableNode node) { for (final SnmpCollection snmpcoll : getSnmpCollections(node.getNodeId(), node.getSnmpPrimaryIpAddr(), node.getSysoid())) { if (m_activepackages.contains(snmpcoll.getPackageName())) { LogUtils.debugf( this, "ScheduleCollectionForNode: package active: %s", snmpcoll.getPackageName()); } else { // schedule discovery link LogUtils.debugf( this, "ScheduleCollectionForNode: Scheduling Discovery Link for Active Package: %s", snmpcoll.getPackageName()); final DiscoveryLink discovery = this.getDiscoveryLink(snmpcoll.getPackageName()); if (discovery.getScheduler() == null) { discovery.setScheduler(m_scheduler); } discovery.schedule(); m_activepackages.add(snmpcoll.getPackageName()); } if (snmpcoll.getScheduler() == null) { snmpcoll.setScheduler(m_scheduler); } LogUtils.debugf( this, "ScheduleCollectionForNode: Scheduling SNMP Collection for Package/NodeId: %s/%d/%s", snmpcoll.getPackageName(), node.getNodeId(), snmpcoll.getInfo()); snmpcoll.schedule(); } }
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]); }
/** * getRanges * * @return a {@link java.util.List} object. */ public List<IPPollRange> getRanges() { final List<IPPollRange> includes = new LinkedList<IPPollRange>(); getReadLock().lock(); try { Long defaultTimeout = null; Integer defaultRetries = null; if (getConfiguration().hasTimeout()) defaultTimeout = getConfiguration().getTimeout(); if (getConfiguration().hasRetries()) defaultRetries = getConfiguration().getRetries(); for (final IncludeRange ir : getConfiguration().getIncludeRangeCollection()) { // Validate IP range; if invalid, then log and discard this range try { InetAddressUtils.toIpAddrBytes(ir.getBegin()); } catch (Throwable e) { LogUtils.warnf( this, "Begin address of discovery range is invalid, discarding: %s", ir.getBegin()); continue; } try { InetAddressUtils.toIpAddrBytes(ir.getEnd()); } catch (Throwable e) { LogUtils.warnf( this, "End address of discovery range is invalid, discarding: %s", ir.getEnd()); continue; } long timeout = 800L; if (ir.hasTimeout()) { timeout = ir.getTimeout(); } else if (defaultTimeout != null) { timeout = defaultTimeout; } int retries = 3; if (ir.hasRetries()) { retries = ir.getRetries(); } else if (defaultRetries != null) { retries = defaultRetries; } try { includes.add(new IPPollRange(ir.getBegin(), ir.getEnd(), timeout, retries)); } catch (final UnknownHostException uhE) { LogUtils.warnf( this, uhE, "Failed to convert address range (%s, %s)", ir.getBegin(), ir.getEnd()); } } return includes; } finally { getReadLock().unlock(); } }
private void addTrap(TrapNotification o) { try { m_backlogQ.add(o); } catch (InterruptedException e) { LogUtils.warnf(this, e, "addTrap: Error adding trap to queue, it was interrupted"); Thread.currentThread().interrupt(); } catch (final FifoQueueException e) { LogUtils.warnf(this, e, "addTrap: Error adding trap to queue"); } }
/** * Create the SNMP trap session and create the communication channel to communicate with eventd. * * @exception java.lang.reflect.UndeclaredThrowableException if an unexpected database, or IO * exception occurs. * @see org.opennms.protocols.snmp.SnmpTrapSession * @see org.opennms.protocols.snmp.SnmpTrapHandler */ public synchronized void onStart() { m_status = STARTING; LogUtils.debugf(this, "start: Initializing the trapd config factory"); m_processor.start(); m_status = RUNNING; LogUtils.debugf(this, "start: Trapd ready to receive traps"); }
@Override @Transactional public NCSComponent addSubcomponent( final String type, final String foreignSource, final String foreignId, final NCSComponent subComponent, final boolean deleteOrphans) { final ComponentIdentifier subComponentId = getIdentifier(subComponent); LogUtils.debugf( this, "addSubcomponent(%s, %s, %s, %s, %s)", type, foreignSource, foreignId, subComponentId, Boolean.valueOf(deleteOrphans)); final NCSComponent component = getComponent(type, foreignSource, foreignId); final ComponentIdentifier id = getIdentifier(component); final ComponentEventQueue ceq = new ComponentEventQueue(); if (component == null) { throw new ObjectRetrievalFailureException( NCSComponent.class, "Unable to locate component with type=" + type + ", foreignSource=" + foreignSource + ", foreignId=" + foreignId); } final NCSComponent updatedSubComponent = addOrUpdateComponents(subComponentId, subComponent, ceq, deleteOrphans); component.addSubcomponent(updatedSubComponent); m_componentDao.update(component); ceq.componentUpdated(id); try { ceq.sendAll(m_eventProxy); } catch (final EventProxyException e) { LogUtils.warnf( this, e, "Component %s added to %s, but an error occured while sending add/delete/update events.", subComponentId, id); } return getComponent(id); }
/** * Adds a file to the queue. * * @param queue the queue * @param mibFile the MIB file */ private void addFileToQueue(List<URL> queue, File mibFile) { try { URL url = mibFile.toURI().toURL(); if (!queue.contains(url)) { LogUtils.debugf(this, "Adding %s to queue ", url); queue.add(url); } } catch (Exception e) { LogUtils.warnf(this, "Can't generate URL from %s", mibFile.getAbsolutePath()); } }
/* (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; }
/** Resumes Trapd */ public void onResume() { if (m_status != PAUSED) { return; } m_status = RESUME_PENDING; LogUtils.debugf(this, "resume: Calling resume on processor"); m_processor.resume(); m_status = RUNNING; LogUtils.debugf(this, "resume: Trapd resumed"); }
/** Pauses Trapd */ public void onPause() { if (m_status != RUNNING) { return; } m_status = PAUSE_PENDING; LogUtils.debugf(this, "pause: Calling pause on processor"); m_processor.pause(); m_status = PAUSED; LogUtils.debugf(this, "pause: Trapd paused"); }
private final void setState(final State oldState, final State newState) { if (!m_state.compareAndSet(oldState, newState)) { LogUtils.debugf( this, "Attempted to move to state %s with state not %s (actual value %s)", newState, oldState, m_state.get()); } else { if (LogUtils.isTraceEnabled(this)) { LogUtils.tracef(this, "Set state to %s\n", newState); } } }
/** * Stops the currently running service. If the service is not running then the command is silently * discarded. */ public synchronized void onStop() { m_status = STOP_PENDING; // shutdown and wait on the background processing thread to exit. LogUtils.debugf(this, "stop: closing communication paths."); try { if (m_registeredForTraps) { LogUtils.debugf(this, "stop: Closing SNMP trap session."); SnmpUtils.unregisterForTraps(this, getInetAddress(), getSnmpTrapPort()); LogUtils.debugf(this, "stop: SNMP trap session closed."); } else { LogUtils.debugf( this, "stop: not attemping to closing SNMP trap session--it was never opened"); } } catch (final IOException e) { LogUtils.warnf(this, e, "stop: exception occurred closing session"); } catch (final IllegalStateException e) { LogUtils.debugf(this, e, "stop: The SNMP session was already closed"); } LogUtils.debugf(this, "stop: Stopping queue processor."); m_processor.stop(); m_eventReader.close(); m_status = STOPPED; LogUtils.debugf(this, "stop: Trapd stopped"); }
/** * 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; }
/** * 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()); } } } }
/** * Load the config from the default config file and create the singleton instance of this factory. * * @exception java.io.IOException Thrown if the specified config file cannot be read * @exception org.exolab.castor.xml.MarshalException Thrown if the file does not conform to the * schema. * @exception org.exolab.castor.xml.ValidationException Thrown if the contents do not match the * required schema. * @throws java.io.IOException if any. * @throws org.exolab.castor.xml.MarshalException if any. * @throws org.exolab.castor.xml.ValidationException if any. */ public static synchronized void init() throws IOException, MarshalException, ValidationException { if (m_loaded) { // init already called - return // to reload, reload() will need to be called return; } final File cfgFile = ConfigFileConstants.getFile(ConfigFileConstants.DISCOVERY_CONFIG_FILE_NAME); LogUtils.debugf(DiscoveryConfigFactory.class, "init: config file path: %s", cfgFile.getPath()); m_singleton = new DiscoveryConfigFactory(cfgFile.getPath()); try { m_singleton.getInitialSleepTime(); m_singleton.getRestartSleepTime(); m_singleton.getIntraPacketDelay(); m_singleton.getConfiguredAddresses(); } catch (final Exception e) { throw new ValidationException( "An error occurred while validating the configuration: " + e, e); } m_loaded = true; }