/** * {@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 void doSql(String contents) { if (getSql() == null) { LOG.info("send: optional sql argument is null."); return; } if (contents == null) { LOG.info("doSql: HTTP reply is null"); return; } LOG.debug("send: compiling expression: {}", getSwitchValue("result-match")); Pattern p = Pattern.compile(getSwitchValue("result-match")); Matcher m = p.matcher(contents); if (m.matches()) { LOG.debug("send: compiled expression ready to run sql: {}", getSql()); MatchTable matches = new MatchTable(m); String sqlString = PropertiesUtils.substitute(getSql(), matches); LOG.debug("send: running sql: {}", sqlString); JdbcTemplate template = new JdbcTemplate(DataSourceFactory.getInstance()); template.execute(sqlString); } else { LOG.info("send: result didn't match, not running sql"); } }
/** onInit */ @Override protected void onInit() { EventIpcManagerFactory.init(); EventIpcManager mgr = EventIpcManagerFactory.getIpcManager(); PassiveStatusKeeper keeper = getPassiveStatusKeeper(); keeper.setEventManager(mgr); keeper.setDataSource(DataSourceFactory.getInstance()); keeper.init(); }
/** * This method determines what label should be associated with a particular node. A database * connection is retrieved from the Vault. * * <p>WARNING: A properly instantiated and initialized Vault class object is required prior to * calling this method. This method will initially only be called from the WEB UI. * * @param nodeID Unique identifier of the node to be updated. * @return NodeLabel Object containing label and source values * @throws java.sql.SQLException if any. * @deprecated Update this to use modern DAO methods instead of raw SQL */ public NodeLabelJDBCImpl computeLabel(final int nodeID) throws SQLException { final Connection dbConnection = DataSourceFactory.getInstance().getConnection(); final DBUtils d = new DBUtils(NodeLabelJDBCImpl.class, dbConnection); try { return computeLabel(nodeID, null); } finally { d.cleanUp(); } }
/** * This method updates the 'nodelabel' and 'nodelabelsource' fields of the 'node' table for the * specified nodeID. A database connection is retrieved from the Vault. * * <p>WARNING: A properly instantiated and initialized Vault class object is required prior to * calling this method. This method will initially only be called from the WEB UI. * * @param nodeID Unique identifier of the node to be updated. * @param nodeLabel Object containing label and source values. * @throws java.sql.SQLException if any. * @deprecated Use a {@link NodeDao#update(org.opennms.netmgt.model.OnmsNode)} method call instead */ public void assignLabel(final int nodeID, final NodeLabelJDBCImpl nodeLabel) throws SQLException { final Connection dbConnection = DataSourceFactory.getInstance().getConnection(); final DBUtils d = new DBUtils(NodeLabelJDBCImpl.class, dbConnection); try { assignLabel(nodeID, nodeLabel, dbConnection); } finally { d.cleanUp(); } }
@Before public void setUp() throws Exception { MockLogAppender.setupLogging(); MockDatabase db = new MockDatabase(); DataSourceFactory.setInstance(db); RrdUtils.setStrategy(m_strategy); m_provisioner = new OpenNMSProvisioner(); m_eventManager = new MockEventIpcManager(); m_provisioner.setEventManager(m_eventManager); m_capsdConfig = new TestCapsdConfigManager(CAPSD_CONFIG); CapsdConfigFactory.setInstance(m_capsdConfig); m_pollerConfig = new TestPollerConfigManager(POLLER_CONFIG, "localhost", false); PollerConfigFactory.setInstance(m_pollerConfig); m_provisioner.setCapsdConfig(m_capsdConfig); m_provisioner.setPollerConfig(m_pollerConfig); InputStream configStream = ConfigurationTestUtils.getInputStreamForConfigFile("opennms-server.xml"); OpennmsServerConfigFactory onmsSvrConfig = new OpennmsServerConfigFactory(configStream); configStream.close(); OpennmsServerConfigFactory.setInstance(onmsSvrConfig); configStream = ConfigurationTestUtils.getInputStreamForConfigFile("database-schema.xml"); DatabaseSchemaConfigFactory.setInstance(new DatabaseSchemaConfigFactory(configStream)); configStream.close(); configStream = ConfigurationTestUtils.getInputStreamForResource( this, "/org/opennms/netmgt/capsd/collectd-configuration.xml"); CollectdConfigFactory.setInstance( new CollectdConfigFactory( configStream, onmsSvrConfig.getServerName(), onmsSvrConfig.verifyServer())); configStream.close(); JdbcTemplate jdbcTemplate = new JdbcTemplate(db); m_syncer = new JdbcCapsdDbSyncer(); m_syncer.setJdbcTemplate(jdbcTemplate); m_syncer.setOpennmsServerConfig(OpennmsServerConfigFactory.getInstance()); m_syncer.setCapsdConfig(m_capsdConfig); m_syncer.setPollerConfig(m_pollerConfig); m_syncer.setCollectdConfig(CollectdConfigFactory.getInstance()); m_syncer.setNextSvcIdSql(db.getNextServiceIdStatement()); m_syncer.afterPropertiesSet(); m_syncer.syncServices(); m_provisioner.setCapsdDbSyncer(m_syncer); }
/** * Retrieves a current record from the database based upon the key fields of <em>nodeID</em> and * <em>ipAddr</em>. If the record cannot be found then a null reference is returned. * * @param nid The node id key * @param addr The ip address. * @param sid The service id. * @return The loaded entry or null if one could not be found. */ public static DbIfServiceEntry get(int nid, InetAddress addr, int sid) throws SQLException { Connection db = null; try { db = DataSourceFactory.getInstance().getConnection(); return get(db, nid, addr, sid); } finally { try { if (db != null) { db.close(); } } catch (SQLException e) { LOG.warn("Exception closing JDBC connection", e); } } }
/** * Retrieves a current record from the database based upon the key fields of <em>nodeID</em> and * <em>ipAddr</em>. If the record cannot be found then a null reference is returned. * * @param nid The node id key * @param addr The ip address. * @param ifIndex The interface index. * @return The loaded entry or null if one could not be found. */ public static DbIpInterfaceEntry get(int nid, InetAddress addr, int ifIndex) throws SQLException { Connection db = null; try { db = DataSourceFactory.getInstance().getConnection(); return get(db, nid, addr, ifIndex); } finally { try { if (db != null) { db.close(); } } catch (SQLException e) { ThreadCategory.getInstance(DbIpInterfaceEntry.class) .warn("Exception closing JDBC connection", e); } } }
/** * Retrieve all the interfaces and services from the database, and keep them in the user session. * * @param userSession Current user working session * @param nodeId Id of the node to manage */ private List<ManagedInterface> getInterfaces(HttpSession userSession, int nodeId) throws SQLException { Connection connection = null; List<ManagedInterface> allInterfaces = new ArrayList<ManagedInterface>(); int lineCount = 0; final DBUtils d = new DBUtils(getClass()); try { connection = DataSourceFactory.getInstance().getConnection(); d.watch(connection); PreparedStatement ifaceStmt = connection.prepareStatement(INTERFACE_QUERY); d.watch(ifaceStmt); ifaceStmt.setInt(1, nodeId); ResultSet ifaceResults = ifaceStmt.executeQuery(); d.watch(ifaceResults); while (ifaceResults.next()) { lineCount++; ManagedInterface newInterface = new ManagedInterface(); newInterface.setNodeid(nodeId); newInterface.setAddress(ifaceResults.getString(1)); newInterface.setStatus(ifaceResults.getString(2)); allInterfaces.add(newInterface); PreparedStatement svcStmt = connection.prepareStatement(SERVICE_QUERY); d.watch(svcStmt); svcStmt.setInt(1, nodeId); svcStmt.setString(2, newInterface.getAddress()); ResultSet svcResults = svcStmt.executeQuery(); d.watch(svcResults); while (svcResults.next()) { lineCount++; ManagedService newService = new ManagedService(); newService.setId(svcResults.getInt(1)); newService.setName(svcResults.getString(2)); newService.setStatus(svcResults.getString(3)); newInterface.addService(newService); } } userSession.setAttribute("lineItems.nodemanagement", Integer.valueOf(lineCount)); } finally { d.cleanUp(); } return allInterfaces; }
/** * Updates the interface information in the configured database. If the interfaca does not exist * the a new row in the table is created. If the element already exists then it's current row is * updated as needed based upon the current changes to the node. */ public void store() throws SQLException { if (m_changed != 0 || m_fromDb == false) { Connection db = null; try { db = DataSourceFactory.getInstance().getConnection(); store(db); if (db.getAutoCommit() == false) db.commit(); } finally { try { if (db != null) db.close(); } catch (SQLException e) { LOG.warn("Exception closing JDBC connection", e); } } } return; }
public DbIfServiceEntry[] getServices() throws SQLException { DbIfServiceEntry[] entries = null; Connection db = null; try { db = DataSourceFactory.getInstance().getConnection(); entries = getServices(db); } finally { try { if (db != null) { db.close(); } } catch (SQLException e) { log().warn("Exception closing JDBC connection", e); } } return entries; }
/** * getCurrentAssetNodesList * * @return a {@link java.util.List} object. * @throws java.sql.SQLException if any. */ public List<Integer> getCurrentAssetNodesList() throws SQLException { List<Integer> list = new ArrayList<Integer>(); final DBUtils d = new DBUtils(getClass()); try { Connection conn = DataSourceFactory.getInstance().getConnection(); d.watch(conn); Statement stmt = conn.createStatement(); d.watch(stmt); ResultSet rs = stmt.executeQuery("SELECT NODEID FROM ASSETS"); d.watch(rs); while (rs.next()) { list.add(Integer.valueOf(rs.getInt("NODEID"))); } } finally { d.cleanUp(); } return list; }
@Before public void setUp() throws Exception { m_assertLevel = Level.WARN; // System.setProperty("mock.logLevel", "DEBUG"); // System.setProperty("mock.debug", "true"); MockUtil.println("------------ Begin Test --------------------------"); MockLogAppender.setupLogging(); m_network = new MockNetwork(); m_network.setCriticalService("ICMP"); m_network.addNode(1, "Router"); m_network.addInterface("192.168.1.1"); m_network.addService("ICMP"); m_network.addService("SMTP"); m_network.addService("SNMP"); m_network.addInterface("192.168.1.2"); m_network.addService("ICMP"); m_network.addService("SMTP"); m_network.addNode(2, "Server"); m_network.addInterface("192.168.1.3"); m_network.addService("ICMP"); m_network.addService("HTTP"); m_network.addService("SMTP"); m_network.addService("SNMP"); m_network.addNode(3, "Firewall"); m_network.addInterface("192.168.1.4"); m_network.addService("SMTP"); m_network.addService("HTTP"); m_network.addInterface("192.168.1.5"); m_network.addService("SMTP"); m_network.addService("HTTP"); m_network.addNode(4, "DownNode"); m_network.addInterface("192.168.1.6"); m_network.addService("SNMP"); // m_network.addInterface("fe80:0000:0000:0000:0231:f982:0123:4567"); // m_network.addService("SNMP"); m_db = new MockDatabase(); m_db.populate(m_network); DataSourceFactory.setInstance(m_db); // DemandPollDao demandPollDao = new DemandPollDaoHibernate(m_db); // demandPollDao.setAllocateIdStmt(m_db // .getNextSequenceValStatement("demandPollNxtId")); // m_demandPollDao = demandPollDao; m_pollerConfig = new MockPollerConfig(m_network); m_pollerConfig.setNextOutageIdSql(m_db.getNextOutageIdStatement()); m_pollerConfig.setNodeOutageProcessingEnabled(true); m_pollerConfig.setCriticalService("ICMP"); m_pollerConfig.addPackage("TestPackage"); m_pollerConfig.addDowntime(1000L, 0L, -1L, false); m_pollerConfig.setDefaultPollInterval(1000L); m_pollerConfig.populatePackage(m_network); m_pollerConfig.addPackage("TestPkg2"); m_pollerConfig.addDowntime(1000L, 0L, -1L, false); m_pollerConfig.setDefaultPollInterval(2000L); m_pollerConfig.addService(m_network.getService(2, "192.168.1.3", "HTTP")); m_anticipator = new EventAnticipator(); m_outageAnticipator = new OutageAnticipator(m_db); m_eventMgr = new MockEventIpcManager(); m_eventMgr.setEventWriter(m_db); m_eventMgr.setEventAnticipator(m_anticipator); m_eventMgr.addEventListener(m_outageAnticipator); m_eventMgr.setSynchronous(false); QueryManager queryManager = new DefaultQueryManager(); queryManager.setDataSource(m_db); DefaultPollContext pollContext = new DefaultPollContext(); pollContext.setEventManager(m_eventMgr); pollContext.setLocalHostName("localhost"); pollContext.setName("Test.DefaultPollContext"); pollContext.setPollerConfig(m_pollerConfig); pollContext.setQueryManager(queryManager); PollableNetwork network = new PollableNetwork(pollContext); m_poller = new Poller(); m_poller.setDataSource(m_db); m_poller.setEventManager(m_eventMgr); m_poller.setNetwork(network); m_poller.setQueryManager(queryManager); m_poller.setPollerConfig(m_pollerConfig); m_poller.setPollOutagesConfig(m_pollerConfig); MockOutageConfig config = new MockOutageConfig(); config.setGetNextOutageID(m_db.getNextOutageIdStatement()); RrdUtils.setStrategy(new NullRrdStrategy()); // m_outageMgr = new OutageManager(); // m_outageMgr.setEventMgr(m_eventMgr); // m_outageMgr.setOutageMgrConfig(config); // m_outageMgr.setDbConnectionFactory(m_db); }