use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.
the class HostResourceSwRunMonitor method poll.
/**
* {@inheritDoc}
*
* <P>
* The poll() method is responsible for polling the specified address for
* SNMP service availability.
* </P>
* @exception RuntimeException
* Thrown for any uncrecoverable errors.
*/
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
InetAddress ipaddr = svc.getAddress();
// Retrieve this interface's SNMP peer object
//
final SnmpAgentConfig agentConfig = getAgentConfig(svc, parameters);
final String hostAddress = InetAddressUtils.str(ipaddr);
LOG.debug("poll: setting SNMP peer attribute for interface {}", hostAddress);
// Get configuration parameters
//
// This should never need to be overridden, but it can be in order to be used with similar tables.
String serviceNameOid = ParameterMap.getKeyedString(parameters, "service-name-oid", HOSTRESOURCE_SW_NAME_OID);
// This should never need to be overridden, but it can be in order to be used with similar tables.
String serviceStatusOid = ParameterMap.getKeyedString(parameters, "service-status-oid", HOSTRESOURCE_SW_STATUS_OID);
// This is the string that represents the service name to be monitored.
String serviceName = ParameterMap.getKeyedString(parameters, "service-name", null);
// The service name may appear in the table more than once. If this is set to true, all values must match the run level.
String matchAll = ParameterMap.getKeyedString(parameters, "match-all", "false");
// This is one of:
// running(1),
// runnable(2), -- waiting for resource
// -- (i.e., CPU, memory, IO)
// notRunnable(3), -- loaded but waiting for event
// invalid(4) -- not loaded
//
// This represents the maximum run-level, i.e. 2 means either running(1) or runnable(2) pass.
String runLevel = ParameterMap.getKeyedString(parameters, "run-level", "2");
// If "match-all" is true, there can be an optional "min-services" and "max-services" parameters that can define a range. The service is up if:
// a) services_count >= min-services and services_count <= max-services
// b) either one is not defined, then only one has to pass.
// c) neither are defined, the monitor acts just like it used to - checking all instances to see if they are all running.
// It is assumed that all services would have to pass the minimum run state test, no matter what the count.
int minServices = ParameterMap.getKeyedInteger(parameters, "min-services", -1);
int maxServices = ParameterMap.getKeyedInteger(parameters, "max-services", -1);
// set timeout and retries on SNMP peer object
//
agentConfig.setTimeout(ParameterMap.getKeyedInteger(parameters, "timeout", agentConfig.getTimeout()));
agentConfig.setRetries(ParameterMap.getKeyedInteger(parameters, "retry", ParameterMap.getKeyedInteger(parameters, "retries", agentConfig.getRetries())));
agentConfig.setPort(ParameterMap.getKeyedInteger(parameters, "port", agentConfig.getPort()));
LOG.debug("poll: service= SNMP address= {}", agentConfig);
PollStatus status = PollStatus.unavailable("HostResourceSwRunMonitor service not found, addr=" + hostAddress + ", service-name=" + serviceName);
// Establish SNMP session with interface
//
int matches = 0;
try {
LOG.debug("HostResourceSwRunMonitor.poll: SnmpAgentConfig address: {}", agentConfig);
if (serviceName == null) {
status.setReason("HostResourceSwRunMonitor no service-name defined, addr=" + hostAddress);
LOG.warn("HostResourceSwRunMonitor.poll: No Service Name Defined! ");
return status;
}
if (minServices > 0 && maxServices > 0 && minServices >= maxServices) {
String reason = "min-services(" + minServices + ") should be less than max-services(" + maxServices + ")";
status.setReason("HostResourceSwRunMonitor " + reason + ", addr=" + hostAddress + ", service-name=" + serviceName);
LOG.warn("HostResourceSwRunMonitor.poll: {}.", reason);
return status;
}
// This updates two maps: one of instance and service name, and one of instance and status.
final SnmpObjId serviceNameOidId = SnmpObjId.get(serviceNameOid);
final SnmpObjId serviceStatusOidId = SnmpObjId.get(serviceStatusOid);
final Map<SnmpInstId, SnmpValue> nameResults = new HashMap<SnmpInstId, SnmpValue>();
final Map<SnmpInstId, SnmpValue> statusResults = new HashMap<SnmpInstId, SnmpValue>();
RowCallback callback = new RowCallback() {
@Override
public void rowCompleted(SnmpRowResult result) {
nameResults.put(result.getInstance(), result.getValue(serviceNameOidId));
statusResults.put(result.getInstance(), result.getValue(serviceStatusOidId));
}
};
TimeoutTracker tracker = new TimeoutTracker(parameters, agentConfig.getRetries(), agentConfig.getTimeout());
tracker.reset();
tracker.startAttempt();
TableTracker tableTracker = new TableTracker(callback, serviceNameOidId, serviceStatusOidId);
try (SnmpWalker walker = SnmpUtils.createWalker(agentConfig, "HostResourceSwRunMonitor", tableTracker)) {
walker.start();
walker.waitFor();
String error = walker.getErrorMessage();
if (error != null && !error.trim().equals("")) {
LOG.warn(error);
return PollStatus.unavailable(error);
}
}
// Iterate over the list of running services
for (SnmpInstId nameInstance : nameResults.keySet()) {
final SnmpValue name = nameResults.get(nameInstance);
final SnmpValue value = statusResults.get(nameInstance);
// See if the service name is in the list of running services
if (name != null && value != null && match(serviceName, StringUtils.stripExtraQuotes(name.toString()))) {
matches++;
LOG.debug("poll: HostResourceSwRunMonitor poll succeeded, addr={}, service-name={}, value={}", hostAddress, serviceName, nameResults.get(nameInstance));
// Using the instance of the service, get its status and see if it meets the criteria
if (meetsCriteria(value, "<=", runLevel)) {
status = PollStatus.available(tracker.elapsedTimeInMillis());
// If we get here, that means the service passed the criteria, if only one match is desired we exit.
if ("false".equals(matchAll)) {
return status;
}
// if we get here, that means the meetsCriteria test failed.
} else {
String reason = "HostResourceSwRunMonitor poll failed, addr=" + hostAddress + ", service-name=" + serviceName + ", status=" + statusResults.get(nameInstance);
LOG.debug(reason);
status = PollStatus.unavailable(reason);
return status;
}
}
}
LOG.debug("poll: HostResourceSwRunMonitor the number of matches found for {} was {}", serviceName, matches);
} catch (NumberFormatException e) {
String reason = "Number operator used on a non-number " + e.getMessage();
LOG.debug(reason);
status = PollStatus.unavailable(reason);
} catch (IllegalArgumentException e) {
String reason = "Invalid SNMP Criteria: " + e.getMessage();
LOG.debug(reason);
status = PollStatus.unavailable(reason);
} catch (Throwable t) {
String reason = "Unexpected exception during SNMP poll of interface " + hostAddress;
LOG.debug(reason, t);
status = PollStatus.unavailable(reason);
}
// This will be executed only if match-all=true
boolean minOk = minServices > 0 ? matches >= minServices : true;
boolean maxOk = maxServices > 0 ? matches <= maxServices : true;
if (!minOk && maxServices < 0) {
// failed min-services only
String reason = "HostResourceSwRunMonitor poll failed: service-count(" + matches + ") >= min-services(" + minServices + "), addr=" + hostAddress + ", service-name=" + serviceName;
LOG.debug(reason);
status = PollStatus.unavailable(reason);
}
if (!maxOk && minServices < 0) {
// failed max-services only
String reason = "HostResourceSwRunMonitor poll failed: service-count(" + matches + ") <= max-services(" + maxServices + "), addr=" + hostAddress + ", service-name=" + serviceName;
LOG.debug(reason);
status = PollStatus.unavailable(reason);
}
if ((!minOk || !maxOk) && minServices > 0 && maxServices > 0) {
// failed both (bad range)
String reason = "HostResourceSwRunMonitor poll failed: min-services(" + minServices + ") >= service-count(" + matches + ") <= max-services(" + maxServices + "), addr=" + hostAddress + ", service-name=" + serviceName;
LOG.debug(reason);
status = PollStatus.unavailable(reason);
}
return status;
}
use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.
the class HttpPostMonitor method poll.
/**
* {@inheritDoc}
*
* Poll the specified address for service availability.
*
* During the poll an attempt is made to execute the named method (with optional input) connect on the specified port. If
* the exec on 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 set the service
* status to SERVICE_AVAILABLE and return.
*/
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
// Process parameters
TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
// Port
int port = ParameterMap.getKeyedInteger(parameters, PARAMETER_PORT, DEFAULT_PORT);
// URI
String strURI = ParameterMap.getKeyedString(parameters, PARAMETER_URI, DEFAULT_URI);
// Username
String strUser = ParameterMap.getKeyedString(parameters, PARAMETER_USERNAME, null);
// Password
String strPasswd = ParameterMap.getKeyedString(parameters, PARAMETER_PASSWORD, null);
// BannerMatch
String strBannerMatch = ParameterMap.getKeyedString(parameters, PARAMETER_BANNER, null);
// Scheme
String strScheme = ParameterMap.getKeyedString(parameters, PARAMETER_SCHEME, DEFAULT_SCHEME);
// Payload
String strPayload = ParameterMap.getKeyedString(parameters, PARAMETER_PAYLOAD, null);
// Mimetype
String strMimetype = ParameterMap.getKeyedString(parameters, PARAMETER_MIMETYPE, DEFAULT_MIMETYPE);
// Charset
String strCharset = ParameterMap.getKeyedString(parameters, PARAMETER_CHARSET, DEFAULT_CHARSET);
// SSLFilter
boolean boolSSLFilter = ParameterMap.getKeyedBoolean(parameters, PARAMETER_SSLFILTER, DEFAULT_SSLFILTER);
// Get the address instance.
InetAddress ipAddr = svc.getAddress();
final String hostAddress = InetAddressUtils.str(ipAddr);
LOG.debug("poll: address = {}, port = {}, {}", hostAddress, port, tracker);
// Give it a whirl
PollStatus serviceStatus = PollStatus.unavailable();
for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
HttpClientWrapper clientWrapper = null;
try {
tracker.startAttempt();
clientWrapper = HttpClientWrapper.create().setConnectionTimeout(tracker.getSoTimeout()).setSocketTimeout(tracker.getSoTimeout()).setRetries(DEFAULT_RETRY);
if (boolSSLFilter) {
clientWrapper.trustSelfSigned(strScheme);
}
HttpEntity postReq;
if (strUser != null && strPasswd != null) {
clientWrapper.addBasicCredentials(strUser, strPasswd);
}
try {
postReq = new StringEntity(strPayload, ContentType.create(strMimetype, strCharset));
} catch (final UnsupportedCharsetException e) {
serviceStatus = PollStatus.unavailable("Unsupported encoding encountered while constructing POST body " + e);
break;
}
URIBuilder ub = new URIBuilder();
ub.setScheme(strScheme);
ub.setHost(hostAddress);
ub.setPort(port);
ub.setPath(strURI);
LOG.debug("HttpPostMonitor: Constructed URL is {}", ub);
HttpPost post = new HttpPost(ub.build());
post.setEntity(postReq);
CloseableHttpResponse response = clientWrapper.execute(post);
LOG.debug("HttpPostMonitor: Status Line is {}", response.getStatusLine());
if (response.getStatusLine().getStatusCode() > 399) {
LOG.info("HttpPostMonitor: Got response status code {}", response.getStatusLine().getStatusCode());
LOG.debug("HttpPostMonitor: Received server response: {}", response.getStatusLine());
LOG.debug("HttpPostMonitor: Failing on bad status code");
serviceStatus = PollStatus.unavailable("HTTP(S) Status code " + response.getStatusLine().getStatusCode());
break;
}
LOG.debug("HttpPostMonitor: Response code is valid");
double responseTime = tracker.elapsedTimeInMillis();
HttpEntity entity = response.getEntity();
InputStream responseStream = entity.getContent();
String Strresponse = IOUtils.toString(responseStream);
if (Strresponse == null)
continue;
LOG.debug("HttpPostMonitor: banner = {}", Strresponse);
LOG.debug("HttpPostMonitor: responseTime= {}ms", responseTime);
// Could it be a regex?
if (!Strings.isNullOrEmpty(strBannerMatch) && strBannerMatch.startsWith("~")) {
if (!Strresponse.matches(strBannerMatch.substring(1))) {
serviceStatus = PollStatus.unavailable("Banner does not match Regex '" + strBannerMatch + "'");
break;
} else {
serviceStatus = PollStatus.available(responseTime);
}
} else {
if (Strresponse.indexOf(strBannerMatch) > -1) {
serviceStatus = PollStatus.available(responseTime);
} else {
serviceStatus = PollStatus.unavailable("Did not find expected Text '" + strBannerMatch + "'");
break;
}
}
} catch (final URISyntaxException e) {
final String reason = "URISyntaxException for URI: " + strURI + " " + e.getMessage();
LOG.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
break;
} catch (final Exception e) {
final String reason = "Exception: " + e.getMessage();
LOG.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
break;
} finally {
IOUtils.closeQuietly(clientWrapper);
}
}
// return the status of the service
return serviceStatus;
}
use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.
the class JDBCMonitor method poll.
/**
* {@inheritDoc}
*
* Network interface to poll for a given service. Make sure you're using the
* latest (at least 5.5) <a
* href="http://www.sybase.com/detail_list/1,6902,2912,00.html">JConnect
* version </a> or the plugin will not be able to tell exactly if the
* service is up or not.
* @see org.opennms.netmgt.poller.ServiceMonitor#SERVICE_AVAILABLE
* @see org.opennms.netmgt.poller.ServiceMonitor#SERVICE_UNAVAILABLE
* @see org.opennms.netmgt.poller.ServiceMonitor#SERVICE_UNRESPONSIVE
* @see <a
* href="http://manuals.sybase.com/onlinebooks/group-jc/jcg0550e/prjdbc/@Generic__BookTextView/9332;pt=1016#X">Error
* codes for JConnect </a>
*/
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
// Assume that the service is down
PollStatus status = PollStatus.unavailable();
Driver driver = null;
Connection con = null;
Statement statement = null;
ResultSet resultset = null;
if (parameters == null) {
throw new NullPointerException("parameter cannot be null");
}
String driverClass = ParameterMap.getKeyedString(parameters, "driver", DBTools.DEFAULT_JDBC_DRIVER);
try {
driver = (Driver) Class.forName(driverClass).newInstance();
LOG.debug("Loaded JDBC driver: {}", driverClass);
} catch (Throwable exp) {
throw new RuntimeException("Unable to load driver class: " + exp.toString(), exp);
}
LOG.info("Loaded JDBC driver");
// Get the JDBC url host part
InetAddress ipAddr = svc.getAddress();
String url = null;
url = DBTools.constructUrl(ParameterMap.getKeyedString(parameters, "url", DBTools.DEFAULT_URL), ipAddr.getCanonicalHostName());
LOG.debug("JDBC url: {}", url);
TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
String db_user = ParameterMap.getKeyedString(parameters, "user", DBTools.DEFAULT_DATABASE_USER);
String db_pass = ParameterMap.getKeyedString(parameters, "password", DBTools.DEFAULT_DATABASE_PASSWORD);
Properties props = new Properties();
props.setProperty("user", db_user);
props.setProperty("password", db_pass);
props.setProperty("timeout", String.valueOf(tracker.getTimeoutInSeconds()));
for (tracker.reset(); tracker.shouldRetry(); tracker.nextAttempt()) {
try {
con = driver.connect(url, props);
// We are connected, upgrade the status to unresponsive
status = PollStatus.unresponsive();
if (con == null) {
LOG.error("Wrong kind of JDBC driver ({}) to connect to the JDBC URL: {}", driverClass, url);
status = PollStatus.unavailable("Wrong kind of JDBC driver to connect to the JDBC URL");
break;
} else {
LOG.debug("JDBC Connection Established");
tracker.startAttempt();
status = checkDatabaseStatus(con, parameters);
if (status.isAvailable()) {
double responseTime = tracker.elapsedTimeInMillis();
status = PollStatus.available(responseTime);
LOG.debug("JDBC service is AVAILABLE on: {}", ipAddr.getCanonicalHostName());
LOG.debug("poll: responseTime= {}ms", responseTime);
break;
}
}
// end if con
} catch (SQLException sqlEx) {
String reason = "JDBC service is not responding on: " + ipAddr.getCanonicalHostName() + ", " + sqlEx.getSQLState() + ", " + sqlEx.toString();
LOG.debug(reason, sqlEx);
status = PollStatus.unavailable(reason);
} finally {
closeResultSet(resultset);
closeStmt(statement);
closeConnection(con);
}
}
return status;
}
use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.
the class JDBCMonitor method checkDatabaseStatus.
/**
* <p>checkDatabaseStatus</p>
*
* @param con a {@link java.sql.Connection} object.
* @param parameters a {@link java.util.Map} object.
* @return a {@link org.opennms.netmgt.poller.PollStatus} object.
*/
public PollStatus checkDatabaseStatus(Connection con, Map<String, Object> parameters) {
PollStatus status = PollStatus.unavailable("Unable to retrieve database catalogs");
ResultSet resultset = null;
try {
// We are connected, upgrade the status to unresponsive
status = PollStatus.unresponsive();
DatabaseMetaData metadata = con.getMetaData();
resultset = metadata.getCatalogs();
while (resultset.next()) {
resultset.getString(1);
}
// The query worked, assume than the server is ok
if (resultset != null) {
status = PollStatus.available();
}
} catch (SQLException sqlEx) {
String reason = "JDBC service failed to retrieve metadata: " + sqlEx.getSQLState() + ", " + sqlEx.toString();
LOG.debug(reason, sqlEx);
status = PollStatus.unavailable(reason);
} finally {
closeResultSet(resultset);
}
return status;
}
use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.
the class JDBCStoredProcedureMonitor method checkDatabaseStatus.
/**
* {@inheritDoc}
*/
@Override
public PollStatus checkDatabaseStatus(Connection con, Map<String, Object> parameters) {
PollStatus status = PollStatus.unavailable();
CallableStatement cs = null;
try {
boolean bPass = false;
String storedProcedure = ParameterMap.getKeyedString(parameters, "stored-procedure", null);
if (storedProcedure == null)
return status;
String schemaName = ParameterMap.getKeyedString(parameters, "schema", "test");
String procedureCall = "{ ? = call " + schemaName + "." + storedProcedure + "()}";
cs = con.prepareCall(procedureCall);
LOG.debug("Calling stored procedure: {}", procedureCall);
cs.registerOutParameter(1, java.sql.Types.BIT);
cs.executeUpdate();
bPass = cs.getBoolean(1);
LOG.debug("Stored procedure returned: {}", bPass);
// If the query worked, assume than the server is ok
if (bPass) {
status = PollStatus.available();
}
} catch (SQLException sqlEx) {
String reason = "JDBC stored procedure call not functional: " + sqlEx.getSQLState() + ", " + sqlEx.toString();
LOG.debug(reason, sqlEx);
status = PollStatus.unavailable(reason);
} finally {
closeStmt(cs);
}
return status;
}
Aggregations