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<String>();
// 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 PollerResponseDTOTest method getPollerResponse.
public static PollerResponseDTO getPollerResponse() throws UnknownHostException {
PollerResponseDTO dto = new PollerResponseDTO();
PollStatus pollStatus = PollStatus.available();
pollStatus.setTimestamp(new Date(0));
dto.setPollStatus(pollStatus);
return dto;
}
use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.
the class BSFMonitor method executeScript.
private synchronized PollStatus executeScript(MonitoredService svc, Map<String, Object> map) {
PollStatus pollStatus = PollStatus.unavailable();
String fileName = ParameterMap.getKeyedString(map, "file-name", null);
String lang = ParameterMap.getKeyedString(map, "lang-class", null);
String langEngine = ParameterMap.getKeyedString(map, "bsf-engine", null);
String[] langExtensions = ParameterMap.getKeyedString(map, "file-extensions", "").split(",");
String runType = ParameterMap.getKeyedString(map, "run-type", "eval");
File file = new File(fileName);
try {
if (lang == null)
lang = BSFManager.getLangFromFilename(fileName);
if (langEngine != null && lang != null && langExtensions.length > 0) {
//We register the scripting engine again no matter what since
//BSFManager doesn't let us know what engine is currently registered
//for this language and it might not be the same as what we want.
LOG.debug("Registering scripting engine '{}' for '{}'", langEngine, lang);
BSFManager.registerScriptingEngine(lang, langEngine, langExtensions);
}
if (file.exists() && file.canRead()) {
String code = IOUtils.getStringFromReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));
HashMap<String, String> results = new HashMap<String, String>();
LinkedHashMap<String, Number> times = new LinkedHashMap<String, Number>();
// Declare some beans that can be used inside the script
m_bsfManager.declareBean("map", map, Map.class);
m_bsfManager.declareBean("ip_addr", svc.getIpAddr(), String.class);
m_bsfManager.declareBean("node_id", svc.getNodeId(), int.class);
m_bsfManager.declareBean("node_label", svc.getNodeLabel(), String.class);
m_bsfManager.declareBean("svc_name", svc.getSvcName(), String.class);
m_bsfManager.declareBean("bsf_monitor", this, BSFMonitor.class);
m_bsfManager.declareBean("results", results, Map.class);
m_bsfManager.declareBean("times", times, Map.class);
for (final Entry<String, Object> entry : map.entrySet()) {
m_bsfManager.declareBean(entry.getKey(), entry.getValue(), String.class);
}
pollStatus = PollStatus.unknown("The script did not update the service status");
long startTime = System.currentTimeMillis();
if ("eval".equals(runType)) {
LOG.debug("m_bsfManager's hashCode is " + (m_bsfManager == null ? "null" : m_bsfManager.hashCode()) + "; lang is " + lang + "; code's hashCode is " + (code == null ? "null" : code.hashCode()));
results.put("status", m_bsfManager.eval(lang, "BSFMonitor", 0, 0, code).toString());
} else if ("exec".equals(runType)) {
m_bsfManager.exec(lang, "BSFMonitor", 0, 0, code);
} else {
LOG.warn("Invalid run-type parameter value '{}' for service '{}'. Only 'eval' and 'exec' are supported.", runType, svc.getSvcName());
throw new RuntimeException("Invalid run-type '" + runType + "'");
}
long endTime = System.currentTimeMillis();
if (!times.containsKey(PollStatus.PROPERTY_RESPONSE_TIME)) {
times.put(PollStatus.PROPERTY_RESPONSE_TIME, endTime - startTime);
}
if (STATUS_UNKNOWN.equals(results.get("status"))) {
pollStatus = PollStatus.unknown(results.get("reason"));
} else if (STATUS_UNRESPONSIVE.equals(results.get("status"))) {
pollStatus = PollStatus.unresponsive(results.get("reason"));
} else if (STATUS_AVAILABLE.equals(results.get("status"))) {
pollStatus = PollStatus.available();
} else if (STATUS_UNAVAILABLE.equals(results.get("status"))) {
pollStatus = PollStatus.unavailable(results.get("reason"));
} else {
// Fall through to the old default of treating any other non-OK
// code as meaning unavailable and also carrying the reason code
pollStatus = PollStatus.unavailable(results.get("status"));
}
LOG.debug("Setting {} times for service '{}'", times.size(), svc.getSvcName());
pollStatus.setProperties(times);
if ("exec".equals(runType) && !results.containsKey("status")) {
LOG.warn("The exec script '{}' for service '{}' never put a 'status' entry in the 'results' bean. Exec scripts should put this entry with a value of 'OK' for up.", fileName, svc.getSvcName());
}
} else {
LOG.warn("Cannot locate or read BSF script file '{}'. Marking service '{}' down.", fileName, svc.getSvcName());
pollStatus = PollStatus.unavailable("Cannot locate or read BSF script file: " + fileName);
}
} catch (BSFException e) {
LOG.warn("BSFMonitor poll for service '{}' failed with BSFException: {}", svc.getSvcName(), e.getMessage(), e);
pollStatus = PollStatus.unavailable(e.getMessage());
} catch (FileNotFoundException e) {
LOG.warn("Could not find BSF script file '{}'. Marking service '{}' down.", fileName, svc.getSvcName());
pollStatus = PollStatus.unavailable("Could not find BSF script file: " + fileName);
} catch (IOException e) {
pollStatus = PollStatus.unavailable(e.getMessage());
LOG.warn("BSFMonitor poll for service '{}' failed with IOException: {}", svc.getSvcName(), e.getMessage(), e);
} catch (Throwable e) {
// Catch any RuntimeException throws
pollStatus = PollStatus.unavailable(e.getMessage());
LOG.warn("BSFMonitor poll for service '{}' failed with unexpected throwable: {}", svc.getSvcName(), e.getMessage(), e);
} finally {
//remove the beans we've declared so the manager is ready for the next poll
undeclareBeans(map);
}
return pollStatus;
}
Aggregations