use of org.opennms.core.utils.TimeoutTracker in project opennms by OpenNMS.
the class HttpMonitor method poll.
/**
* {@inheritDoc}
*
* Poll the specified address for HTTP service availability.
*
* During the poll an attempt is made to connect on the specified port(s) (by default TCP
* ports 80, 8080, 8888). If the connection request is successful, an HTTP 'GET' command is
* sent to the interface. The response is parsed and a return code extracted and verified.
* Provided that the interface's response is valid we set the service status to
* SERVICE_AVAILABLE and return.
*/
@Override
public PollStatus poll(final MonitoredService svc, final Map<String, Object> parameters) {
final InetAddress addr = svc.getAddress();
final String nodeLabel = svc.getNodeLabel();
// Cycle through the port list
//
int currentPort = -1;
final HttpMonitorClient httpClient = new HttpMonitorClient(nodeLabel, addr, new TreeMap<String, Object>(parameters));
for (int portIndex = 0; portIndex < determinePorts(httpClient.getParameters()).length && httpClient.getPollStatus() != PollStatus.SERVICE_AVAILABLE; portIndex++) {
currentPort = determinePorts(httpClient.getParameters())[portIndex];
httpClient.setTimeoutTracker(new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT));
LOG.debug("Port = {}, Address = {}, {}", currentPort, addr, httpClient.getTimeoutTracker());
httpClient.setCurrentPort(currentPort);
String serviceInfo = new StringBuilder(addr.toString()).append(":").append(svc.getSvcName()).append(":").append(currentPort).toString();
for (httpClient.getTimeoutTracker().reset(); httpClient.getTimeoutTracker().shouldRetry() && httpClient.getPollStatus() != PollStatus.SERVICE_AVAILABLE; httpClient.getTimeoutTracker().nextAttempt()) {
try {
httpClient.getTimeoutTracker().startAttempt();
httpClient.connect();
LOG.debug("HttpMonitor: connected to host: {} on port: {}", addr, currentPort);
httpClient.sendHttpCommand();
if (httpClient.isEndOfStream()) {
continue;
}
httpClient.setResponseTime(httpClient.getTimeoutTracker().elapsedTimeInMillis());
logResponseTimes(httpClient.getResponseTime(), httpClient.getCurrentLine());
if (httpClient.getPollStatus() == PollStatus.SERVICE_AVAILABLE && StringUtils.isNotBlank(httpClient.getResponseText())) {
httpClient.setPollStatus(PollStatus.SERVICE_UNAVAILABLE);
httpClient.readLinedMatching();
if (httpClient.isEndOfStream()) {
continue;
}
httpClient.read();
if (!httpClient.isResponseTextFound()) {
String message = "Matching text: [" + httpClient.getResponseText() + "] not found in body of HTTP response for " + serviceInfo;
LOG.debug(message);
httpClient.setReason("Matching text: [" + httpClient.getResponseText() + "] not found in body of HTTP response");
}
}
} catch (NoRouteToHostException e) {
LOG.warn("checkStatus: No route to host exception while polling {}", serviceInfo, e);
// Will cause outer for(;;) to terminate
portIndex = determinePorts(httpClient.getParameters()).length;
httpClient.setReason("No route to host exception");
} catch (SocketTimeoutException e) {
LOG.info("checkStatus: HTTP socket connection for service {} timed out with {}", serviceInfo, httpClient.getTimeoutTracker().toString());
httpClient.setReason("HTTP connection timeout");
} catch (InterruptedIOException e) {
LOG.info(String.format("checkStatus: HTTP connection for service {} interrupted after {} bytes transferred with {}", serviceInfo, e.bytesTransferred, httpClient.getTimeoutTracker().toString()), e);
httpClient.setReason(String.format("HTTP connection interrupted, %d bytes transferred", e.bytesTransferred));
} catch (ConnectException e) {
LOG.warn("Connection exception for {}", serviceInfo, e);
httpClient.setReason("HTTP connection exception on port: " + determinePorts(httpClient.getParameters())[portIndex] + ": " + e.getMessage());
} catch (IOException e) {
String exceptionClass = e.getClass().getSimpleName();
LOG.warn("{} while polling {}", exceptionClass, serviceInfo, e);
httpClient.setReason("IOException while polling address: " + addr + ": " + e.getMessage());
} catch (Throwable e) {
String exceptionClass = e.getClass().getSimpleName();
LOG.warn("Unexpected {} while polling {}", exceptionClass, serviceInfo, e);
httpClient.setReason("Unexpected exception while polling address: " + addr + ": " + e.getMessage());
} finally {
httpClient.closeConnection();
}
}
// end for (attempts)
}
// end for (ports)
return httpClient.determinePollStatusResponse();
}
use of org.opennms.core.utils.TimeoutTracker 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.core.utils.TimeoutTracker 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.core.utils.TimeoutTracker in project opennms by OpenNMS.
the class LdapMonitor method poll.
/**
* {@inheritDoc}
*
* Poll the specified address for service availability.
*
* During the poll an attempt is made to connect the service.
*
* Provided that the interface's response is valid we set the service status
* to SERVICE_AVAILABLE and return.
*/
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
int serviceStatus = PollStatus.SERVICE_UNAVAILABLE;
String reason = null;
final TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
// get the parameters
//
final int ldapVersion = ParameterMap.getKeyedInteger(parameters, "version", LDAPConnection.LDAP_V3);
final int ldapPort = determinePort(parameters);
final String searchBase = ParameterMap.getKeyedString(parameters, "searchbase", DEFAULT_BASE);
final String searchFilter = ParameterMap.getKeyedString(parameters, "searchfilter", DEFAULT_FILTER);
final String password = (String) parameters.get("password");
final String ldapDn = (String) parameters.get("dn");
String address = InetAddrUtils.str(svc.getAddress());
// first just try a connection to the box via socket. Just in case there
// is
// a no way to route to the address, don't iterate through the retries,
// as a
// NoRouteToHost exception will only be thrown after about 5 minutes,
// thus tying
// up the thread
Double responseTime = null;
Socket socket = null;
try {
socket = new Socket();
socket.connect(new InetSocketAddress(svc.getAddress(), ldapPort), tracker.getConnectionTimeout());
socket.setSoTimeout(tracker.getSoTimeout());
LOG.debug("LdapMonitor: connected to host: {} on port: {}", address, ldapPort);
// We're connected, so upgrade status to unresponsive
serviceStatus = PollStatus.SERVICE_UNRESPONSIVE;
if (socket != null)
socket.close();
// lets detect the service
LDAPConnection lc = new LDAPConnection(new TimeoutLDAPSocket(tracker.getSoTimeout()));
for (tracker.reset(); tracker.shouldRetry() && !(serviceStatus == PollStatus.SERVICE_AVAILABLE); tracker.nextAttempt()) {
LOG.debug("polling LDAP on {}, {}", address, tracker);
// connect to the ldap server
tracker.startAttempt();
try {
lc.connect(address, ldapPort);
LOG.debug("connected to LDAP server {} on port {}", address, ldapPort);
} catch (LDAPException e) {
LOG.debug("could not connect to LDAP server {} on port {}", address, ldapPort);
reason = "could not connect to LDAP server " + address + " on port " + ldapPort;
continue;
}
// bind if possible
if (ldapDn != null && password != null) {
try {
lc.bind(ldapVersion, ldapDn, password.getBytes());
LOG.debug("bound to LDAP server version {} with distinguished name {}", ldapVersion, ldapDn);
LOG.debug("poll: responseTime= {}ms", tracker.elapsedTimeInMillis());
} catch (LDAPException e) {
try {
lc.disconnect();
} catch (LDAPException ex) {
LOG.debug(ex.getMessage());
}
LOG.debug("could not bind to LDAP server version {} with distinguished name {}", ldapVersion, ldapDn);
reason = "could not bind to LDAP server version " + ldapVersion + " with distinguished name " + ldapDn;
continue;
}
}
// do a quick search and see if any results come back
boolean attributeOnly = true;
String[] attrs = { LDAPConnection.NO_ATTRS };
int searchScope = LDAPConnection.SCOPE_ONE;
LOG.debug("running search {} from {}", searchFilter, searchBase);
LDAPSearchResults results = null;
int msLimit = (int) tracker.getTimeoutInMillis();
int serverLimit = (int) tracker.getTimeoutInSeconds() + 1;
LDAPSearchConstraints cons = new LDAPSearchConstraints(msLimit, serverLimit, // dereference: default = never
LDAPSearchConstraints.DEREF_NEVER, // maxResults: default = 1000
1000, // doReferrals: default = false
false, // batchSize: default = 1
1, // handler: default = null
null, // hop_limit: default = 10
10);
try {
results = lc.search(searchBase, searchScope, searchFilter, attrs, attributeOnly, cons);
if (results != null && results.hasMore()) {
responseTime = tracker.elapsedTimeInMillis();
LOG.debug("search yielded {} result(s)", results.getCount());
serviceStatus = PollStatus.SERVICE_AVAILABLE;
} else {
LOG.debug("no results found from search");
reason = "No results found from search";
serviceStatus = PollStatus.SERVICE_UNAVAILABLE;
}
} catch (LDAPException e) {
try {
lc.disconnect();
} catch (LDAPException ex) {
LOG.debug(ex.getMessage());
}
LOG.debug("could not perform search {} from {}", searchFilter, searchBase);
reason = "could not perform search " + searchFilter + " from " + searchBase;
continue;
}
try {
lc.disconnect();
LOG.debug("disconected from LDAP server {} on port {}", address, ldapPort);
} catch (LDAPException e) {
LOG.debug(e.getMessage());
}
}
} catch (ConnectException e) {
LOG.debug("connection refused to host {}", address, e);
reason = "connection refused to host " + address;
} catch (NoRouteToHostException e) {
LOG.debug("No route to host {}", address, e);
reason = "No route to host " + address;
} catch (InterruptedIOException e) {
LOG.debug("did not connect to host with {}", tracker);
reason = "did not connect to host with " + tracker;
} catch (Throwable t) {
LOG.debug("An undeclared throwable exception caught contacting host {}", address, t);
reason = "An undeclared throwable exception caught contacting host " + address;
}
return PollStatus.get(serviceStatus, reason, responseTime);
}
use of org.opennms.core.utils.TimeoutTracker in project opennms by OpenNMS.
the class AvailabilityMonitor method poll.
/** {@inheritDoc} */
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
TimeoutTracker timeoutTracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
for (timeoutTracker.reset(); timeoutTracker.shouldRetry(); timeoutTracker.nextAttempt()) {
try {
timeoutTracker.startAttempt();
if (svc.getAddress().isReachable(timeoutTracker.getSoTimeout())) {
return PollStatus.available(timeoutTracker.elapsedTimeInMillis());
}
} catch (IOException e) {
LOG.debug("Unable to contact {}", svc.getIpAddr(), e);
}
}
String reason = svc + " failed to respond";
LOG.debug(reason);
return PollStatus.unavailable(reason);
}
Aggregations