use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.
the class SSLCertMonitor method poll.
/**
* {@inheritDoc}
*
* Poll the specified address for HTTP service availability.
*
* During the poll an attempt is made to connect on the specified port. If
* the connection request is successful, check the X509Certificates provided
* by our peer and check that our time is between the certificates start and
* end time.
* 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) {
TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
// Port
int port = ParameterMap.getKeyedInteger(parameters, PARAMETER_PORT, DEFAULT_PORT);
if (port == DEFAULT_PORT) {
throw new RuntimeException("Required parameter 'port' is not present in supplied properties.");
}
// Remaining days
int validityDays = ParameterMap.getKeyedInteger(parameters, PARAMETER_DAYS, DEFAULT_DAYS);
if (validityDays <= 0) {
throw new RuntimeException("Required parameter 'days' must be a positive value.");
}
// Server name (optional)
final String serverName = PropertiesUtils.substitute(ParameterMap.getKeyedString(parameters, PARAMETER_SERVER_NAME, ""), getServiceProperties(svc));
// Calculate validity range
Calendar calValid = this.getCalendarInstance();
Calendar calCurrent = this.getCalendarInstance();
calValid.setTimeInMillis(calCurrent.getTimeInMillis());
calValid.add(Calendar.DAY_OF_MONTH, validityDays);
Calendar calBefore = this.getCalendarInstance();
Calendar calAfter = this.getCalendarInstance();
// Get the address instance
InetAddress ipAddr = svc.getAddress();
final String hostAddress = InetAddressUtils.str(ipAddr);
LOG.debug("poll: address={}, port={}, serverName={}, {}", hostAddress, port, serverName, tracker);
// Give it a whirl
PollStatus serviceStatus = PollStatus.unavailable();
for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
Socket socket = null;
try {
tracker.startAttempt();
socket = new Socket();
socket.connect(new InetSocketAddress(ipAddr, port), tracker.getConnectionTimeout());
socket.setSoTimeout(tracker.getSoTimeout());
LOG.debug("Connected to host: {} on port: {}", ipAddr, port);
SSLSocket sslSocket = SocketUtils.wrapSocketInSslContext(socket, null, null);
// We're connected, so upgrade status to unresponsive
serviceStatus = PollStatus.unresponsive();
// Use the server name as as SNI host name if available
if (!Strings.isNullOrEmpty(serverName)) {
final SSLParameters sslParameters = sslSocket.getSSLParameters();
sslParameters.setServerNames(ImmutableList.of(new SNIHostName(serverName)));
sslSocket.setSSLParameters(sslParameters);
// Check certificates host name
if (!new StrictHostnameVerifier().verify(serverName, sslSocket.getSession())) {
serviceStatus = PollStatus.unavailable("Host name verification failed - certificate common name is invalid");
continue;
}
}
Certificate[] certs = sslSocket.getSession().getPeerCertificates();
for (int i = 0; i < certs.length && !serviceStatus.isAvailable(); i++) {
if (certs[i] instanceof X509Certificate) {
X509Certificate certx = (X509Certificate) certs[i];
LOG.debug("Checking validity against dates: [current: {}, valid: {}], NotBefore: {}, NotAfter: {}", calCurrent.getTime(), calValid.getTime(), certx.getNotBefore(), certx.getNotAfter());
calBefore.setTime(certx.getNotBefore());
calAfter.setTime(certx.getNotAfter());
if (calCurrent.before(calBefore)) {
LOG.debug("Certificate is invalid, current time is before start time");
serviceStatus = PollStatus.unavailable("Certificate is invalid, current time is before start time");
break;
} else if (calCurrent.before(calAfter)) {
if (calValid.before(calAfter)) {
LOG.debug("Certificate is valid, and does not expire before validity check date");
serviceStatus = PollStatus.available(tracker.elapsedTimeInMillis());
break;
} else {
String reason = "Certificate is valid, but will expire in " + validityDays + " days.";
LOG.debug(reason);
serviceStatus = PollStatus.unavailable(reason);
break;
}
} else {
LOG.debug("Certificate has expired.");
serviceStatus = PollStatus.unavailable("Certificate has expired.");
break;
}
}
}
} catch (NoRouteToHostException e) {
String reason = "No route to host exception for address " + hostAddress;
LOG.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
// Break out of for(;;)
break;
} catch (InterruptedIOException e) {
String reason = "did not connect to host with " + tracker;
LOG.debug(reason);
serviceStatus = PollStatus.unavailable(reason);
} catch (ConnectException e) {
String reason = "Connection exception for address: " + ipAddr;
LOG.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
} catch (IOException e) {
String reason = "IOException while polling address: " + ipAddr;
LOG.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
} finally {
try {
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.fillInStackTrace();
LOG.debug("poll: Error closing socket.", e);
}
}
}
return serviceStatus;
}
use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.
the class MailTransportMonitor method readTestMessage.
private PollStatus readTestMessage(final MailTransportParameters mailParms) {
LOG.debug("readTestMessage: Beginning read mail test.");
PollStatus status = PollStatus.unavailable("Test not completed.");
final long interval = mailParms.getReadTestAttemptInterval();
if (mailParms.isEnd2EndTestInProgress()) {
LOG.debug("Initially delaying read test: {} because end to end test is in progress.", mailParms.getReadTestAttemptInterval());
if (delayTest(status, interval) == PollStatus.SERVICE_UNKNOWN) {
return status;
}
}
Store mailStore = null;
Folder mailFolder = null;
try {
final JavaMailer readMailer = new JavaMailer(mailParms.getJavamailProperties());
setReadMailProperties(mailParms, readMailer);
final TimeoutTracker tracker = new TimeoutTracker(mailParms.getParameterMap(), mailParms.getRetries(), mailParms.getTimeout());
for (tracker.reset(); tracker.shouldRetry(); tracker.nextAttempt()) {
tracker.startAttempt();
if (tracker.getAttempt() > 0) {
if (delayTest(status, interval) == PollStatus.SERVICE_UNKNOWN) {
LOG.warn("readTestMessage: Status set to: {} during delay, exiting test.", status);
break;
}
}
LOG.debug("readTestMessage: reading mail attempt: {}, elapsed time: {}ms.", (tracker.getAttempt() + 1), String.format("%.2f", tracker.elapsedTimeInMillis()));
try {
mailStore = readMailer.getSession().getStore();
mailFolder = retrieveMailFolder(mailParms, mailStore);
mailFolder.open(Folder.READ_WRITE);
} catch (final MessagingException e) {
if (tracker.shouldRetry()) {
LOG.warn("readTestMessage: error reading INBOX", e);
closeStore(mailStore, mailFolder);
//try again to get mail Folder from Store
continue;
} else {
LOG.warn("readTestMessage: error reading INBOX", e);
return PollStatus.down(e.getLocalizedMessage());
}
}
if (mailFolder.isOpen() && (mailParms.getReadTest().getSubjectMatch() != null || mailParms.isEnd2EndTestInProgress())) {
status = processMailSubject(mailParms, mailFolder);
if (status.getStatusCode() == PollStatus.SERVICE_AVAILABLE) {
break;
}
}
}
} catch (final JavaMailerException e) {
status = PollStatus.down(e.getLocalizedMessage());
} finally {
closeStore(mailStore, mailFolder);
}
return status;
}
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;
}
use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.
the class MinionHeartbeatMonitor method poll.
@Override
public PollStatus poll(final MonitoredService svc, final Map<String, Object> parameters) {
// Minions send heartbeat every 30 seconds - we check that we can skip not more than one beat
final int period = 2 * ParameterMap.getKeyedInteger(parameters, "period", 30 * 1000);
// Get the minion to test whereas the minion ID is the nodes foreign ID by convention
final OnmsNode node = nodeDao.get().get(svc.getNodeId());
final OnmsMinion minion = minionDao.get().findById(node.getForeignId());
// Calculate the time since the last heartbeat was received
final long lastSeen = System.currentTimeMillis() - minion.getLastUpdated().getTime();
final PollStatus status;
if (lastSeen <= period) {
status = PollStatus.available();
} else if (ManagementFactory.getRuntimeMXBean().getUptime() < period) {
status = PollStatus.unknown("JVM has not been started long enough to process a heartbeat.");
} else {
status = PollStatus.unavailable(String.format("Last heartbeat was %.2f seconds ago", lastSeen / 1000.0));
}
return status;
}
Aggregations