use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.
the class LocationDataServiceIT method getDown.
private PollStatus getDown(final Date date) {
final PollStatus ps = PollStatus.down("butt itches");
ps.setTimestamp(date);
return ps;
}
use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.
the class AvailCalculatorTest method testGetAvailabilityOneStatus.
@Test
public void testGetAvailabilityOneStatus() {
Date endTime = new Date(System.currentTimeMillis());
Date startTime = new Date(endTime.getTime() - 100);
PollStatus pollStatus = PollStatus.unavailable();
Date timestamp = new Date(endTime.getTime() - 50);
OnmsLocationSpecificStatus statusChange = createStatusChange(pollStatus, timestamp);
TimeChunker chunker = new TimeChunker((int) (endTime.getTime() - startTime.getTime()), startTime, endTime);
AvailCalculator calculator = new AvailCalculator(chunker);
calculator.onStatusChange(statusChange);
chunker.getNextSegment();
double uptimePercent = calculator.getAvailabilityFor(getServices(), 0);
assertEquals(0.5, uptimePercent, 0.00);
}
use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.
the class DnsMonitor method pollDNS.
private PollStatus pollDNS(final TimeoutTracker timeoutTracker, final int port, final InetAddress address, final String lookup, final List<Integer> fatalCodes, int minAnswers, int maxAnswers) {
final String addr = InetAddressUtils.str(address);
for (timeoutTracker.reset(); timeoutTracker.shouldRetry(); timeoutTracker.nextAttempt()) {
try {
final Name name = Name.fromString(lookup, Name.root);
final SimpleResolver resolver = new SimpleResolver();
resolver.setAddress(new InetSocketAddress(addr, port));
resolver.setLocalAddress((InetSocketAddress) null);
double timeout = timeoutTracker.getSoTimeout() / 1000d;
resolver.setTimeout((timeout < 1 ? 1 : (int) timeout));
final Record question = Record.newRecord(name, Type.A, DClass.IN);
final Message query = Message.newQuery(question);
PollStatus status;
timeoutTracker.startAttempt();
final Message response = resolver.send(query);
double responseTime = timeoutTracker.elapsedTimeInMillis();
final Integer rcode = response.getHeader().getRcode();
LOG.debug("received response code: {}", rcode);
if (fatalCodes.contains(rcode)) {
status = PollStatus.unavailable("Received an invalid DNS response for address: " + addr);
LOG.debug(status.getReason());
return status;
} else if (minAnswers != DEFAULT_MIN_ANSWERS || maxAnswers != DEFAULT_MAX_ANSWERS) {
int numAnswers = response.getSectionArray(Section.ANSWER).length;
boolean tooFewAnswers = numAnswers < minAnswers;
boolean tooManyAnswers = numAnswers > maxAnswers;
if (tooFewAnswers) {
status = PollStatus.unavailable("Response contained only " + numAnswers + " answer(s), but at least " + minAnswers + " answers(s) are needed.");
LOG.warn(status.getReason());
return status;
}
if (tooManyAnswers) {
status = PollStatus.unavailable("Response contained " + numAnswers + " answer(s), but " + maxAnswers + " or fewer answers(s) are needed.");
LOG.warn(status.getReason());
return status;
}
status = PollStatus.up(responseTime);
LOG.debug("valid DNS response received with {} answer(s), responseTime = {}ms", numAnswers, responseTime);
return status;
} else {
status = PollStatus.up(responseTime);
LOG.debug("valid DNS response received, responseTime = {}ms", responseTime);
return status;
}
} catch (final InterruptedIOException e) {
// No response received, retry without marking the poll failed. If we get this condition over and over until
// the retries are exhausted, it will leave serviceStatus null and we'll get the log message at the bottom
} catch (final NoRouteToHostException e) {
String reason1 = "No route to host exception for address: " + addr;
LOG.debug(reason1, e);
return PollStatus.unavailable(reason1);
} catch (final ConnectException e) {
String reason1 = "Connection exception for address: " + addr;
LOG.debug(reason1, e);
return PollStatus.unavailable(reason1);
} catch (final IOException e) {
String reason1 = "IOException while polling address: " + addr + " " + e.getMessage();
LOG.debug(reason1, e);
return PollStatus.unavailable(reason1);
}
}
String reason = "Never received valid DNS response for address: " + addr;
LOG.debug(reason);
return PollStatus.unavailable(reason);
}
use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.
the class FtpMonitor method poll.
// read()
/**
* {@inheritDoc}
*
* Poll the specified address for FTP service availability.
*
* During the poll an attempt is made to connect on the specified port (by
* default TCP port 21). If the connection request is successful, the banner
* line generated by the interface is parsed and if the extracted return
* code indicates that we are talking to an FTP server we continue. Next, an
* FTP 'QUIT' command is sent. 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) {
// Get the parameters
TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
int port = ParameterMap.getKeyedInteger(parameters, "port", DEFAULT_PORT);
String userid = ParameterMap.getKeyedString(parameters, "userid", null);
String password = ParameterMap.getKeyedString(parameters, "password", null);
// Extract the address
InetAddress ipAddr = svc.getAddress();
PollStatus serviceStatus = PollStatus.unavailable();
for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
LOG.debug("FtpMonitor.poll: Polling interface: {} {}", InetAddressUtils.str(ipAddr), tracker);
Socket socket = null;
try {
// create a connected socket
tracker.startAttempt();
socket = new Socket();
socket.connect(new InetSocketAddress(ipAddr, port), tracker.getConnectionTimeout());
socket.setSoTimeout(tracker.getSoTimeout());
LOG.debug("FtpMonitor: connected to host: {} on port: {}", ipAddr, port);
// We're connected, so upgrade status to unresponsive
serviceStatus = PollStatus.unresponsive();
BufferedReader lineRdr = new BufferedReader(new InputStreamReader(socket.getInputStream()));
FtpResponse bannerResponse = FtpResponse.readResponse(lineRdr);
if (bannerResponse.isSuccess()) {
// Attempt to login if userid and password available
boolean loggedInSuccessfully = false;
LOG.debug("FtpMonitor: Banner response successful.");
if (userid == null || userid.length() == 0 || password == null || password.length() == 0) {
loggedInSuccessfully = true;
} else {
FtpResponse.sendCommand(socket, "USER " + userid);
FtpResponse userResponse = FtpResponse.readResponse(lineRdr);
if (userResponse.isSuccess() || userResponse.isIntermediate()) {
LOG.debug("FtpMonitor: User response successful.");
FtpResponse.sendCommand(socket, "PASS " + password);
FtpResponse passResponse = FtpResponse.readResponse(lineRdr);
if (passResponse.isSuccess()) {
LOG.debug("FtpMonitor.poll: Login successful, parsed return code: {}", passResponse.getCode());
loggedInSuccessfully = true;
} else {
LOG.debug("FtpMonitor.poll: Login failed, parsed return code: {}, full response: {}", passResponse.getCode(), passResponse);
loggedInSuccessfully = false;
}
}
}
// Store the response time before we try to quit
double responseTime = tracker.elapsedTimeInMillis();
if (loggedInSuccessfully) {
FtpResponse.sendCommand(socket, "QUIT");
FtpResponse quitResponse = FtpResponse.readResponse(lineRdr);
/*
* Special Cases for success:
*
* Also want to accept the following
* ERROR message generated by some FTP servers
* following a QUIT command without a previous
* successful login:
*
* "530 QUIT : User not logged in. Please login with
* USER and PASS first."
*
* Also want to accept the following ERROR
* message generated by some FTP servers following a
* QUIT command without a previously successful login:
*
* "425 Session is disconnected."
*/
if (quitResponse.isSuccess() || (quitResponse.getCode() == 530) || (quitResponse.getCode() == 425)) {
serviceStatus = PollStatus.available(responseTime);
}
}
}
/*
* If we get this far and the status has not been set
* to available, then something didn't verify during
* the banner checking or login/QUIT command process.
*/
if (!serviceStatus.isAvailable()) {
serviceStatus = PollStatus.unavailable();
}
} catch (NumberFormatException e) {
String reason = "NumberFormatException while polling address: " + ipAddr;
LOG.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
} catch (NoRouteToHostException e) {
String reason = "No route to host exception for address: " + ipAddr;
LOG.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
} 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 {
// Close the socket
if (socket != null) {
socket.close();
}
} catch (IOException e) {
LOG.debug("FtpMonitor.poll: Error closing socket", e);
}
}
}
return serviceStatus;
}
use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.
the class GpMonitor method poll.
// read()
/**
* {@inheritDoc}
*
* Poll the specified address for service availability.
*
* During the poll an attempt is made to call the specified external script
* or program. If the connection request is successful, the banner line
* returned as standard output by the script or program is parsed for a
* partial match with the banner string specified in the poller
* configuration. Provided that the script's response is valid we set the
* service status to SERVICE_AVAILABLE and return.
*
* The timeout is handled by ExecRunner and is also passed as a parameter to
* the script or program being called.
*/
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
LOG.warn("GpMonitor: This poller monitor is deprecated in favor of SystemExecuteMonitor. GpMonitor will be removed in a future release.");
//
// Process parameters
//
TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
String hoption = ParameterMap.getKeyedString(parameters, "hoption", "--hostname");
String toption = ParameterMap.getKeyedString(parameters, "toption", "--timeout");
//
// convert timeout to seconds for ExecRunner
//
String args = ParameterMap.getKeyedString(parameters, "args", null);
// Script
//
String script = ParameterMap.getKeyedString(parameters, "script", null);
if (script == null) {
throw new RuntimeException("GpMonitor: required parameter 'script' is not present in supplied properties.");
}
// BannerMatch
//
String strBannerMatch = (String) parameters.get("banner");
// Script standard output
//
String scriptoutput = "";
// Script error output
//
String scripterror = "";
// Get the address instance.
//
InetAddress ipAddr = svc.getAddress();
final String hostAddress = InetAddressUtils.str(ipAddr);
LOG.debug("poll: address = {}, script = {}, arguments = {}, {}", hostAddress, script, args, tracker);
// Give it a whirl
//
PollStatus serviceStatus = PollStatus.unavailable();
for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
try {
tracker.startAttempt();
int exitStatus = 100;
// Some scripts, such as Nagios check scripts, look for -H and -t versus --hostname and
// --timeout. If the optional parameter option-type is set to short, then the former
// will be used.
int timeoutInSeconds = (int) tracker.getTimeoutInSeconds();
ExecRunner er = new ExecRunner();
er.setMaxRunTimeSecs(timeoutInSeconds);
if (args == null)
exitStatus = er.exec(script + " " + hoption + " " + hostAddress + " " + toption + " " + timeoutInSeconds);
else
exitStatus = er.exec(script + " " + hoption + " " + hostAddress + " " + toption + " " + timeoutInSeconds + " " + args);
double responseTime = tracker.elapsedTimeInMillis();
if (exitStatus != 0) {
scriptoutput = er.getOutString();
String reason = script + " failed with exit code " + exitStatus + ". Standard out: " + scriptoutput;
LOG.debug(reason);
serviceStatus = PollStatus.unavailable(reason);
}
if (er.isMaxRunTimeExceeded()) {
String reason = script + " failed. Timeout exceeded";
LOG.debug(reason);
serviceStatus = PollStatus.unavailable(reason);
} else {
if (exitStatus == 0) {
scriptoutput = er.getOutString();
scripterror = er.getErrString();
if (!scriptoutput.equals(""))
LOG.debug("{} output = {}", script, scriptoutput);
else
LOG.debug("{} returned no output", script);
if (!scripterror.equals(""))
LOG.debug("{} error = {}", script, scripterror);
if (strBannerMatch == null || strBannerMatch.equals("*")) {
serviceStatus = PollStatus.available(responseTime);
} else {
if (scriptoutput.indexOf(strBannerMatch) > -1) {
serviceStatus = PollStatus.available(responseTime);
} else {
serviceStatus = PollStatus.unavailable(script + "banner not contained in output banner='" + strBannerMatch + "' output='" + scriptoutput + "'");
}
}
}
}
} catch (ArrayIndexOutOfBoundsException e) {
String reason = script + " ArrayIndexOutOfBoundsException";
LOG.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
} catch (IOException e) {
String reason = "IOException occurred. Check for proper operation of " + script;
LOG.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
} catch (Throwable e) {
String reason = script + "Exception occurred";
LOG.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
}
}
//
// return the status of the service
//
LOG.debug("poll: GP - serviceStatus= {} {}", serviceStatus, hostAddress);
return serviceStatus;
}
Aggregations