use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.
the class JMXMonitor method poll.
/**
* {@inheritDoc}
*/
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> map) {
final InetAddress ipv4Addr = svc.getAddress();
PollStatus serviceStatus = PollStatus.unavailable();
try {
final Timer timer = new Timer();
final JmxConnectionManager connectionManager = new DefaultConnectionManager(ParameterMap.getKeyedInteger(map, "retry", 3));
final JmxConnectionManager.RetryCallback retryCallback = new JmxConnectionManager.RetryCallback() {
@Override
public void onRetry() {
timer.reset();
}
};
try (JmxServerConnectionWrapper connection = connectionManager.connect(getConnectionName(), ipv4Addr, JmxUtils.convertToStringMap(map), retryCallback)) {
// Start with simple communication
connection.getMBeanServerConnection().getMBeanCount();
// Take time just here to get not influenced by test execution
// time
final long nanoResponseTime = System.nanoTime() - timer.getStartTime();
// Find all variable definitions
final Map<String, Object> variables = Maps.newHashMap();
for (final String key : map.keySet()) {
// Skip fast if it does not start with the prefix
if (!key.startsWith(PARAM_BEAN_PREFIX)) {
continue;
}
// Get the variable name
final String variable = key.substring(PARAM_BEAN_PREFIX.length());
// Get the variable definition
final String definition = ParameterMap.getKeyedString(map, key, null);
// Store wrapper for variable definition
variables.put(variable, ObjectNameWrapper.create(connection.getMBeanServerConnection(), definition));
}
// Find all test definitions
final Map<String, Expression> tests = Maps.newHashMap();
for (final String key : map.keySet()) {
// Skip fast if it does not start with the prefix
if (!key.startsWith(PARAM_TEST_PREFIX)) {
continue;
}
// Get the test name
final String variable = key.substring(PARAM_TEST_PREFIX.length());
// Get the test definition
final String definition = ParameterMap.getKeyedString(map, key, null);
// Build the expression from the definition
final Expression expression = JEXL_ENGINE.createExpression(definition);
// Store expressions
tests.put(variable, expression);
}
// Also handle a single test
if (map.containsKey(PARAM_TEST)) {
// Get the test definition
final String definition = ParameterMap.getKeyedString(map, PARAM_TEST, null);
// Build the expression from the definition
final Expression expression = JEXL_ENGINE.createExpression(definition);
// Store expressions
tests.put(null, expression);
}
// Build the context for all tests
final JexlContext context = new ReadonlyContext(new MapContext(variables));
serviceStatus = PollStatus.up(nanoResponseTime / 1000000.0);
// Execute all tests
for (final Map.Entry<String, Expression> e : tests.entrySet()) {
if (!(boolean) e.getValue().evaluate(context)) {
serviceStatus = PollStatus.down("Test failed: " + e.getKey());
break;
}
}
} catch (JmxServerConnectionException mbse) {
// Number of retries exceeded
String reason = "IOException while polling address: " + ipv4Addr;
LOG.debug(reason);
serviceStatus = PollStatus.unavailable(reason);
}
} catch (Throwable e) {
String reason = "Monitor - failed! " + InetAddressUtils.str(ipv4Addr);
LOG.debug(reason);
serviceStatus = PollStatus.unavailable(reason);
}
return serviceStatus;
}
use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.
the class JolokiaBeanMonitor 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);
// URL
String strURL = ParameterMap.getKeyedString(parameters, PARAMETER_URL, DEFAULT_URL);
// Username
String strUser = ParameterMap.getKeyedString(parameters, PARAMETER_USERNAME, null);
// Password
String strPasswd = ParameterMap.getKeyedString(parameters, PARAMETER_PASSWORD, null);
// AttrName
String strAttrName = ParameterMap.getKeyedString(parameters, PARAMETER_ATTRNAME, null);
// AttrPath
String strAttrPath = ParameterMap.getKeyedString(parameters, PARAMETER_ATTRPATH, null);
// BeanName
String strBeanName = ParameterMap.getKeyedString(parameters, PARAMETER_BEANNAME, null);
// MethodName
String strMethodName = ParameterMap.getKeyedString(parameters, PARAMETER_METHODNAME, null);
// Optional Inputs
String strInput1 = ParameterMap.getKeyedString(parameters, PARAMETER_METHODINPUT1, null);
String strInput2 = ParameterMap.getKeyedString(parameters, PARAMETER_METHODINPUT2, null);
// BannerMatch
String strBannerMatch = ParameterMap.getKeyedString(parameters, PARAMETER_BANNER, null);
// Get the address instance.
InetAddress ipAddr = svc.getAddress();
final String hostAddress = InetAddressUtils.str(ipAddr);
LOGGER.debug("poll: address = " + hostAddress + ", port = " + port + ", " + tracker);
strURL = strURL.replace("${ipaddr}", hostAddress);
strURL = strURL.replace("${port}", ((Integer) port).toString());
LOGGER.debug("poll: final URL address = " + strURL);
// Give it a whirl
PollStatus serviceStatus = PollStatus.unknown("Initialized");
for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
try {
tracker.startAttempt();
J4pClientBuilder j4pClientBuilder = new J4pClientBuilder();
j4pClientBuilder.url(strURL).connectionTimeout(tracker.getConnectionTimeout()).socketTimeout(tracker.getSoTimeout());
if (strUser != null && strPasswd != null) {
j4pClientBuilder.user(strUser).password(strPasswd);
}
J4pClient j4pClient = j4pClientBuilder.build();
LOGGER.debug("JolokiaBeanMonitor: connected to URLhost: " + strURL);
// We're connected, so upgrade status to unresponsive
serviceStatus = PollStatus.unresponsive();
if (strBannerMatch == null || strBannerMatch.length() == 0 || strBannerMatch.equals("*")) {
serviceStatus = PollStatus.available(tracker.elapsedTimeInMillis());
break;
}
// Exec a method or poll an attribute?
String response;
if (strAttrName != null) {
J4pReadRequest readReq = new J4pReadRequest(strBeanName, strAttrName);
readReq.setPreferredHttpMethod("POST");
if (strAttrPath != null) {
readReq.setPath(strAttrPath);
}
J4pReadResponse resp = j4pClient.execute(readReq);
response = resp.getValue().toString();
} else {
J4pExecRequest execReq;
// Default Inputs
if (strInput1 == null && strInput2 == null) {
LOGGER.debug("JolokiaBeanMonitor - execute bean: " + strBeanName + " method: " + strMethodName);
execReq = new J4pExecRequest(strBeanName, strMethodName);
} else if (strInput1 != null && strInput2 == null) {
// Single Input
LOGGER.debug("JolokiaBeanMonitor - execute bean: " + strBeanName + " method: " + strMethodName + " args: " + strInput1);
execReq = new J4pExecRequest(strBeanName, strMethodName, strInput1);
} else {
// Double Input
LOGGER.debug("JolokiaBeanMonitor - execute bean: " + strBeanName + " method: " + strMethodName + " args: " + strInput1 + " " + strInput2);
execReq = new J4pExecRequest(strBeanName, strMethodName, strInput1, strInput2);
}
execReq.setPreferredHttpMethod("POST");
J4pExecResponse resp = j4pClient.execute(execReq);
response = resp.getValue().toString();
}
double responseTime = tracker.elapsedTimeInMillis();
if (response == null) {
continue;
}
LOGGER.debug("poll: banner = " + response);
LOGGER.debug("poll: responseTime = " + responseTime + "ms");
// Could it be a regex?
if (strBannerMatch.charAt(0) == '~') {
if (!response.matches(strBannerMatch.substring(1))) {
serviceStatus = PollStatus.unavailable("Banner does not match Regex '" + strBannerMatch + "'");
} else {
serviceStatus = PollStatus.available(responseTime);
}
} else {
if (response.contains(strBannerMatch)) {
serviceStatus = PollStatus.available(responseTime);
} else {
serviceStatus = PollStatus.unavailable("Did not find expected Text '" + strBannerMatch + "'");
}
}
} catch (J4pConnectException e) {
String reason = "Connection exception for address: " + ipAddr + ":" + port + " " + e.getMessage();
LOGGER.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
break;
} catch (J4pRemoteException e) {
String reason = "Remote exception from J4pRemote: " + e.getMessage();
LOGGER.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
} catch (MalformedObjectNameException e) {
String reason = "Parameters for Jolokia are malformed: " + e.getMessage();
LOGGER.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
} catch (J4pException e) {
String reason = J4pException.class.getSimpleName() + " during Jolokia monitor call: " + e.getMessage();
LOGGER.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
}
}
return serviceStatus;
}
use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.
the class LaTableMonitor 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.
*/
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
PollStatus status = PollStatus.available();
InetAddress ipaddr = svc.getAddress();
ArrayList<String> errorStringReturn = new ArrayList<>();
// 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);
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);
try {
LOG.debug("PrTableMonitor.poll: SnmpAgentConfig address: {}", agentConfig);
SnmpObjId laTableErrorSnmpObject = SnmpObjId.get(laTableErrorFlag);
Map<SnmpInstId, SnmpValue> flagResults = SnmpUtils.getOidValues(agentConfig, "LaTableMonitor", laTableErrorSnmpObject);
if (flagResults.size() == 0) {
LOG.debug("SNMP poll failed: no results, addr={} oid={}", hostAddress, laTableErrorSnmpObject);
return PollStatus.unavailable();
}
for (Map.Entry<SnmpInstId, SnmpValue> e : flagResults.entrySet()) {
LOG.debug("poll: SNMPwalk poll succeeded, addr={} oid={} instance={} value={}", hostAddress, laTableErrorSnmpObject, e.getKey(), e.getValue());
if (e.getValue().toString().equals("1")) {
LOG.debug("LaTableMonitor.poll: found errorFlag=1");
SnmpObjId laTableErrorMsgSnmpObject = SnmpObjId.get(laTableErrorMsg + "." + e.getKey().toString());
String LaErrorMsg = SnmpUtils.get(agentConfig, laTableErrorMsgSnmpObject).toDisplayString();
// Stash the error in an ArrayList to then enumerate over later
errorStringReturn.add(LaErrorMsg);
}
}
// Check the arraylist and construct return value
if (errorStringReturn.size() > 0) {
return PollStatus.unavailable(errorStringReturn.toString());
} else {
return status;
}
} catch (NumberFormatException e) {
String reason1 = "Number operator used on a non-number " + e.getMessage();
LOG.error(reason1, e);
return PollStatus.unavailable(reason1);
} catch (IllegalArgumentException e) {
String reason1 = "Invalid SNMP Criteria: " + e.getMessage();
LOG.error(reason1, e);
return PollStatus.unavailable(reason1);
} catch (Throwable t) {
String reason1 = "Unexpected exception during SNMP poll of interface " + hostAddress;
LOG.warn(reason1);
return PollStatus.unavailable(reason1);
}
}
use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.
the class MailTransportMonitor method poll.
/**
* {@inheritDoc}
*/
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
PollStatus status = null;
try {
final MailTransportParameters mailParms = MailTransportParameters.get(parameters);
try {
if ("${ipaddr}".equals(mailParms.getReadTestHost())) {
mailParms.setReadTestHost(svc.getIpAddr());
}
} catch (final IllegalStateException ise) {
// just ignore, don't have to have a both a read and send test configured
}
try {
if ("${ipaddr}".equals(mailParms.getSendTestHost())) {
mailParms.setSendTestHost(svc.getIpAddr());
}
} catch (final IllegalStateException ise) {
// just ignore, don't have to have a both a read and send test configured
}
parseJavaMailProperties(mailParms);
status = doMailTest(mailParms);
} catch (final IllegalStateException ise) {
// ignore this because we don't have to have both a send and read
} catch (final Throwable e) {
LOG.error("An error occurred while polling.", e);
status = PollStatus.down("Exception from mailer: " + e.getLocalizedMessage());
}
return status;
}
use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.
the class MailTransportMonitor method processMailSubject.
/**
* After a mailbox has been opened, search through the retrieved messages
* for a matching subject.
*
* @param mailParms
* @param mailFolder
* @return a PollStatus indicative of the success of matching a subject or just retieving
* mail folder contents... dependent on configuration.
*/
private PollStatus processMailSubject(final MailTransportParameters mailParms, final Folder mailFolder) {
PollStatus status = PollStatus.unknown();
try {
final String subject = computeMatchingSubject(mailParms);
if (mailFolder.isOpen() && subject != null) {
final Message[] mailMessages = mailFolder.getMessages();
final SearchTerm searchTerm = new SubjectTerm(subject);
final SearchTerm deleteTerm = new HeaderTerm(MTM_HEADER_KEY, m_headerValue);
LOG.debug("searchMailSubject: searching {} message(s) for subject '{}'", mailMessages.length, subject);
boolean delete = false;
boolean found = false;
for (int i = 1; i <= mailMessages.length; i++) {
final Message mailMessage = mailFolder.getMessage(i);
LOG.debug("searchMailSubject: retrieved message subject '{}'", mailMessage.getSubject());
if (mailMessage.match(searchTerm)) {
found = true;
LOG.debug("searchMailSubject: message with subject '{}' found.", subject);
if (mailParms.isEnd2EndTestInProgress()) {
if (!delete)
LOG.debug("searchMailSubject: flagging message with subject '{}' for deletion for end2end test.", subject);
delete = true;
}
}
final boolean deleteAllMail = mailParms.getReadTest().getDeleteAllMail();
final boolean foundMTMHeader = mailMessage.match(deleteTerm);
LOG.debug("searchMailSubject: deleteAllMail = {}, MTM header found = {}", Boolean.toString(deleteAllMail), Boolean.toString(foundMTMHeader));
if (deleteAllMail) {
if (!delete)
LOG.debug("searchMailSubject: flagging message with subject '{}' for deletion because deleteAllMail is set.", subject);
delete = true;
} else if (foundMTMHeader) {
if (!delete)
LOG.debug("searchMailSubject: flagging message with subject '{}' for deletion because we sent it (found header {}={})", subject, MTM_HEADER_KEY, m_headerValue);
delete = true;
}
if (delete) {
mailMessage.setFlag(Flag.DELETED, true);
}
// since we want to delete old messages matchin MTM_HEADER_KEY, we can't break early
// if (found) break;
}
if (!found) {
LOG.debug("searchMailSubject: message with subject: '{}' NOT found.", subject);
status = PollStatus.down("searchMailSubject: matching test message: '" + subject + "', not found.");
} else {
status = PollStatus.available();
}
}
} catch (final MessagingException e) {
return PollStatus.down(e.getLocalizedMessage());
}
return status;
}
Aggregations