use of org.opennms.core.utils.TimeoutTracker in project opennms by OpenNMS.
the class TrivialTimeMonitor method poll.
/**
* {@inheritDoc}
*
* Poll the specified address for service availability.
*
* During the poll an attempt is made to retrieve the time value from the
* remote system. This can be done via either TCP or UDP depending on the
* provided parameters (default TCP). If the time value returned is within
* the specified number of seconds of the local system's clock time, then
* the service is considered available.
*/
@Override
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, "port", DEFAULT_PORT);
// Get the address instance.
//
InetAddress ipAddr = svc.getAddress();
LOG.debug("poll: address = {}, port = {}, tracker = {}", InetAddressUtils.str(ipAddr), port, tracker);
// Get the permissible amount of skew.
//
int allowedSkew = ParameterMap.getKeyedInteger(parameters, "allowed-skew", DEFAULT_ALLOWED_SKEW);
// Determine whether to persist the skew value in addition to the latency
boolean persistSkew = ParameterMap.getKeyedBoolean(parameters, "persist-skew", DEFAULT_PERSIST_SKEW);
// Give it a whirl
//
PollStatus serviceStatus = PollStatus.unavailable();
String protocol = ParameterMap.getKeyedString(parameters, "protocol", DEFAULT_PROTOCOL).toLowerCase();
if (!protocol.equalsIgnoreCase("tcp") && !protocol.equalsIgnoreCase("udp")) {
throw new IllegalArgumentException("Unsupported protocol, only TCP and UDP currently supported");
} else if (protocol.equalsIgnoreCase("udp")) {
// TODO test UDP support
LOG.warn("UDP support is largely untested");
}
if (protocol.equalsIgnoreCase("tcp")) {
serviceStatus = pollTimeTcp(svc, parameters, serviceStatus, tracker, ipAddr, port, allowedSkew, persistSkew);
} else if (protocol.equalsIgnoreCase("udp")) {
serviceStatus = pollTimeUdp(svc, parameters, serviceStatus, tracker, ipAddr, port, allowedSkew, persistSkew);
}
//
return serviceStatus;
}
use of org.opennms.core.utils.TimeoutTracker in project opennms by OpenNMS.
the class NtpMonitor method poll.
/**
* {@inheritDoc}
*
* <P>
* Poll the specified address for NTP service availability.
* </P>
*
* <P>
* During the poll an NTP request query packet is generated. The query is
* sent via UDP socket to the interface at the specified port (by default
* UDP port 123). If a response is received, it is parsed and validated. If
* the NTP was successful the service status is set to SERVICE_AVAILABLE and
* the method returns.
* </P>
*/
@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);
// get the address and NTP address request
//
InetAddress ipAddr = svc.getAddress();
PollStatus serviceStatus = PollStatus.unavailable();
DatagramSocket socket = null;
double responseTime = -1.0;
try {
socket = new DatagramSocket();
// will force the
socket.setSoTimeout(tracker.getSoTimeout());
for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
try {
// Send NTP request
//
byte[] data = new NtpMessage().toByteArray();
DatagramPacket outgoing = new DatagramPacket(data, data.length, ipAddr, port);
tracker.startAttempt();
socket.send(outgoing);
// Get NTP Response
//
// byte[] buffer = new byte[512];
DatagramPacket incoming = new DatagramPacket(data, data.length);
socket.receive(incoming);
responseTime = tracker.elapsedTimeInMillis();
double destinationTimestamp = (System.currentTimeMillis() / 1000.0) + 2208988800.0;
// Validate NTP Response
// IOException thrown if packet does not decode as expected.
NtpMessage msg = new NtpMessage(incoming.getData());
double localClockOffset = ((msg.receiveTimestamp - msg.originateTimestamp) + (msg.transmitTimestamp - destinationTimestamp)) / 2;
LOG.debug("poll: valid NTP request received the local clock offset is {}, responseTime= {}ms", localClockOffset, responseTime);
LOG.debug("poll: NTP message : {}", msg);
serviceStatus = PollStatus.available(responseTime);
} catch (InterruptedIOException ex) {
// Ignore, no response received.
}
}
} catch (NoRouteToHostException e) {
String reason = "No route to host exception for address: " + ipAddr;
LOG.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
} catch (ConnectException e) {
String reason = "Connection exception for address: " + ipAddr;
LOG.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
} catch (IOException ex) {
String reason = "IOException while polling address: " + ipAddr;
LOG.debug(reason, ex);
serviceStatus = PollStatus.unavailable(reason);
} finally {
if (socket != null)
socket.close();
}
//
return serviceStatus;
}
use of org.opennms.core.utils.TimeoutTracker in project opennms by OpenNMS.
the class VmwareMonitor method poll.
/**
* This method queries the Vmware vCenter server for sensor data.
*
* @param svc the monitored service
* @param parameters the parameter map
* @return the poll status for this system
*/
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
final boolean ignoreStandBy = getKeyedBoolean(parameters, "ignoreStandBy", false);
final String vmwareManagementServer = getKeyedString(parameters, VMWARE_MANAGEMENT_SERVER_KEY, null);
final String vmwareManagedEntityType = getKeyedString(parameters, VMWARE_MANAGED_ENTITY_TYPE_KEY, null);
final String vmwareManagedObjectId = getKeyedString(parameters, VMWARE_MANAGED_OBJECT_ID_KEY, null);
final String vmwareMangementServerUsername = getKeyedString(parameters, VMWARE_MANAGEMENT_SERVER_USERNAME_KEY, null);
final String vmwareMangementServerPassword = getKeyedString(parameters, VMWARE_MANAGEMENT_SERVER_PASSWORD_KEY, null);
final TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
PollStatus serviceStatus = PollStatus.unknown();
for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
final VmwareViJavaAccess vmwareViJavaAccess = new VmwareViJavaAccess(vmwareManagementServer, vmwareMangementServerUsername, vmwareMangementServerPassword);
try {
vmwareViJavaAccess.connect();
} catch (MalformedURLException e) {
logger.warn("Error connecting VMware management server '{}': '{}' exception: {} cause: '{}'", vmwareManagementServer, e.getMessage(), e.getClass().getName(), e.getCause());
return PollStatus.unavailable("Error connecting VMware management server '" + vmwareManagementServer + "'");
} catch (RemoteException e) {
logger.warn("Error connecting VMware management server '{}': '{}' exception: {} cause: '{}'", vmwareManagementServer, e.getMessage(), e.getClass().getName(), e.getCause());
return PollStatus.unavailable("Error connecting VMware management server '" + vmwareManagementServer + "'");
}
if (!vmwareViJavaAccess.setTimeout(tracker.getConnectionTimeout())) {
logger.warn("Error setting connection timeout for VMware management server '{}'", vmwareManagementServer);
}
String powerState = "unknown";
if ("HostSystem".equals(vmwareManagedEntityType)) {
HostSystem hostSystem = vmwareViJavaAccess.getHostSystemByManagedObjectId(vmwareManagedObjectId);
if (hostSystem == null) {
return PollStatus.unknown("hostSystem=null");
} else {
HostRuntimeInfo hostRuntimeInfo = hostSystem.getRuntime();
if (hostRuntimeInfo == null) {
return PollStatus.unknown("hostRuntimeInfo=null");
} else {
HostSystemPowerState hostSystemPowerState = hostRuntimeInfo.getPowerState();
if (hostSystemPowerState == null) {
return PollStatus.unknown("hostSystemPowerState=null");
} else {
powerState = hostSystemPowerState.toString();
}
}
}
} else {
if ("VirtualMachine".equals(vmwareManagedEntityType)) {
VirtualMachine virtualMachine = vmwareViJavaAccess.getVirtualMachineByManagedObjectId(vmwareManagedObjectId);
if (virtualMachine == null) {
return PollStatus.unknown("virtualMachine=null");
} else {
VirtualMachineRuntimeInfo virtualMachineRuntimeInfo = virtualMachine.getRuntime();
if (virtualMachineRuntimeInfo == null) {
return PollStatus.unknown("virtualMachineRuntimeInfo=null");
} else {
VirtualMachinePowerState virtualMachinePowerState = virtualMachineRuntimeInfo.getPowerState();
if (virtualMachinePowerState == null) {
return PollStatus.unknown("virtualMachinePowerState=null");
} else {
powerState = virtualMachinePowerState.toString();
}
}
}
} else {
logger.warn("Error getting '{}' for '{}'", vmwareManagedEntityType, vmwareManagedObjectId);
vmwareViJavaAccess.disconnect();
return serviceStatus;
}
}
if ("poweredOn".equals(powerState)) {
serviceStatus = PollStatus.available();
} else {
if (ignoreStandBy && "standBy".equals(powerState)) {
serviceStatus = PollStatus.up();
} else {
serviceStatus = PollStatus.unavailable("The system's state is '" + powerState + "'");
}
}
vmwareViJavaAccess.disconnect();
}
return serviceStatus;
}
use of org.opennms.core.utils.TimeoutTracker in project opennms by OpenNMS.
the class VmwareCimMonitor method poll.
/**
* This method queries the Vmware hypervisor for sensor data.
*
* @param svc the monitored service
* @param parameters the parameter map
* @return the poll status for this system
*/
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
final boolean ignoreStandBy = getKeyedBoolean(parameters, "ignoreStandBy", false);
final String vmwareManagementServer = getKeyedString(parameters, VMWARE_MANAGEMENT_SERVER_KEY, null);
final String vmwareManagedObjectId = getKeyedString(parameters, VMWARE_MANAGED_OBJECT_ID_KEY, null);
final String vmwareMangementServerUsername = getKeyedString(parameters, VMWARE_MANAGEMENT_SERVER_USERNAME_KEY, null);
final String vmwareMangementServerPassword = getKeyedString(parameters, VMWARE_MANAGEMENT_SERVER_PASSWORD_KEY, null);
TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
PollStatus serviceStatus = PollStatus.unknown();
for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
final VmwareViJavaAccess vmwareViJavaAccess = new VmwareViJavaAccess(vmwareManagementServer, vmwareMangementServerUsername, vmwareMangementServerPassword);
try {
vmwareViJavaAccess.connect();
} catch (MalformedURLException e) {
logger.warn("Error connecting VMware management server '{}': '{}' exception: {} cause: '{}'", vmwareManagementServer, e.getMessage(), e.getClass().getName(), e.getCause());
return PollStatus.unavailable("Error connecting VMware management server '" + vmwareManagementServer + "'");
} catch (RemoteException e) {
logger.warn("Error connecting VMware management server '{}': '{}' exception: {} cause: '{}'", vmwareManagementServer, e.getMessage(), e.getClass().getName(), e.getCause());
return PollStatus.unavailable("Error connecting VMware management server '" + vmwareManagementServer + "'");
}
if (!vmwareViJavaAccess.setTimeout(tracker.getConnectionTimeout())) {
logger.warn("Error setting connection timeout for VMware management server '{}'", vmwareManagementServer);
}
HostSystem hostSystem = vmwareViJavaAccess.getHostSystemByManagedObjectId(vmwareManagedObjectId);
String powerState = null;
if (hostSystem == null) {
return PollStatus.unknown("hostSystem=null");
} else {
HostRuntimeInfo hostRuntimeInfo = hostSystem.getRuntime();
if (hostRuntimeInfo == null) {
return PollStatus.unknown("hostRuntimeInfo=null");
} else {
HostSystemPowerState hostSystemPowerState = hostRuntimeInfo.getPowerState();
if (hostSystemPowerState == null) {
return PollStatus.unknown("hostSystemPowerState=null");
} else {
powerState = hostSystemPowerState.toString();
}
}
}
if ("poweredOn".equals(powerState)) {
List<CIMObject> cimObjects = null;
try {
cimObjects = vmwareViJavaAccess.queryCimObjects(hostSystem, "CIM_NumericSensor", svc.getIpAddr());
} catch (Exception e) {
logger.warn("Error retrieving CIM values from host system '{}'", vmwareManagedObjectId, e.getMessage());
vmwareViJavaAccess.disconnect();
return PollStatus.unavailable("Error retrieving cim values from host system '" + vmwareManagedObjectId + "'");
}
boolean success = true;
StringBuffer reason = new StringBuffer("VMware CIM query returned: ");
for (CIMObject cimObject : cimObjects) {
String healthState = vmwareViJavaAccess.getPropertyOfCimObject(cimObject, "HealthState");
String cimObjectName = vmwareViJavaAccess.getPropertyOfCimObject(cimObject, "Name");
if (healthState != null) {
int healthStateInt = Integer.valueOf(healthState).intValue();
if (healthStateInt != 5) {
if (!success) {
reason.append(", ");
}
success = false;
reason.append(cimObjectName + " ");
if (m_healthStates.containsKey(healthStateInt)) {
reason.append("(" + m_healthStates.get(healthStateInt) + ")");
} else {
reason.append("(" + healthStateInt + ")");
}
}
}
}
if (success) {
serviceStatus = PollStatus.available();
} else {
serviceStatus = PollStatus.unavailable(reason.toString());
}
} else {
if (ignoreStandBy && "standBy".equals(powerState)) {
serviceStatus = PollStatus.up();
} else {
serviceStatus = PollStatus.unresponsive("Host system's power state is '" + powerState + "'");
}
}
vmwareViJavaAccess.disconnect();
}
return serviceStatus;
}
use of org.opennms.core.utils.TimeoutTracker in project opennms by OpenNMS.
the class CiscoPingMibMonitor method poll.
/**
* {@inheritDoc}
*
* <P>
* The poll() method is responsible for setting up and following up the IOS
* ping entry that proxies monitoring of the specified address for ICMP
* service availability.
* </P>
* @exception RuntimeException
* Thrown for any unrecoverable errors.
*/
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
final InetAddress targetIpAddr = InetAddrUtils.addr(getKeyedString(parameters, "targetIpAddr", null));
final InetAddress proxyIpAddr = InetAddrUtils.addr(getKeyedString(parameters, "proxyIpAddr", null));
int pingProtocol = 0;
try {
pingProtocol = determineAddrType(targetIpAddr);
} catch (RuntimeException e) {
LOG.debug("Unknown address type - neither IPv4 nor IPv6", e);
return PollStatus.unavailable("Unknown address type - neither IPv4 nor IPv6");
}
// Get configuration parameters into a CiscoPingEntry object
//
CiscoPingEntry pingEntry = new CiscoPingEntry();
pingEntry.setCiscoPingPacketCount(ParameterMap.getKeyedInteger(parameters, PARM_PACKET_COUNT, PARM_PACKET_COUNT_DEFAULT));
pingEntry.setCiscoPingPacketSize(ParameterMap.getKeyedInteger(parameters, PARM_PACKET_SIZE, PARM_PACKET_SIZE_DEFAULT));
pingEntry.setCiscoPingPacketTimeout(ParameterMap.getKeyedInteger(parameters, PARM_PACKET_TIMEOUT, PARM_PACKET_TIMEOUT_DEFAULT));
pingEntry.setCiscoPingPacketDelay(ParameterMap.getKeyedInteger(parameters, PARM_PACKET_DELAY, PARM_PACKET_DELAY_DEFAULT));
pingEntry.setCiscoPingEntryOwner(ParameterMap.getKeyedString(parameters, PARM_ENTRY_OWNER, PARM_ENTRY_OWNER_DEFAULT));
pingEntry.setCiscoPingVrfName(ParameterMap.getKeyedString(parameters, PARM_VRF_NAME, PARM_VRF_NAME_DEFAULT));
pingEntry.setCiscoPingSerialNumber(Double.valueOf(System.currentTimeMillis() / 1000).intValue());
pingEntry.setCiscoPingProtocol(pingProtocol);
pingEntry.setCiscoPingAddress(targetIpAddr);
pingEntry.setCiscoPingEntryStatus(ROWSTATUS_CREATE_AND_GO);
int minSuccessPercent = ParameterMap.getKeyedInteger(parameters, PARM_SUCCESS_PERCENT, PARM_SUCCESS_PERCENT_DEFAULT);
// FIXME: Should the cleanup stuff be fixed to actually use this? Not clear if it really matters.
// int cleanupInterval = ParameterMap.getKeyedInteger(parameters, PARM_CLEANUP_INTERVAL, PARM_CLEANUP_INTERVAL_DEFAULT);
// Retrieve the *proxy* interface's SNMP peer object
//
SnmpAgentConfig agentConfig = getAgentConfig(svc, parameters);
LOG.debug("poll: setting SNMP peer attribute for interface {}", proxyIpAddr.getHostAddress());
// set timeout and retries on SNMP peer object
//
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("Setting up CISCO-PING-MIB proxy poll for service {} on interface {} -- {}", svc.getSvcName(), targetIpAddr, pingEntry);
PollStatus serviceStatus = null;
TimeoutTracker timeoutTracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
// Send the SET-REQUEST PDU to create the ciscoPingEntry in createAndGo mode
SnmpValue[] setResult = SnmpUtils.set(agentConfig, pingEntry.generateCreateOids(), pingEntry.generateCreateValues());
if (setResult == null) {
LOG.warn("SNMP SET operation unsuccessful for proxy-ping entry for target {} -- {}", targetIpAddr, pingEntry);
return PollStatus.unknown("SNMP SET failed for ciscoPingTable entry on proxy interface " + proxyIpAddr + " with instance ID " + pingEntry.getCiscoPingSerialNumber());
}
// a good starting point.
try {
Thread.sleep(pingEntry.calculateMinInitialWait() * 2);
} catch (InterruptedException e) {
}
// Now check whether the ping has completed and, if so, whether it succeeded and its times
SnmpValue[] statusValues = null;
for (timeoutTracker.reset(); (timeoutTracker.shouldRetry() && (statusValues == null || statusValues.length < 6 || statusValues[5].toInt() != 1)); timeoutTracker.nextAttempt()) {
statusValues = SnmpUtils.get(agentConfig, pingEntry.generateResultsOids());
}
// If we didn't get the results back, mark the service as unknown
if (statusValues == null || (statusValues.length == 1 && statusValues[0] == null)) {
LOG.warn("SNMP GET operation unsuccessful for proxy-ping entry for target {} -- {}", targetIpAddr, pingEntry);
return PollStatus.unknown("SNMP GET failed for ciscoPingTable entry on proxy interface " + proxyIpAddr + " with instance ID " + pingEntry.getCiscoPingSerialNumber());
}
// mark the service unknown
if (statusValues.length < 6) {
LOG.warn("Proxy-ping entry did not indicate whether ping completed after retries exhausted for target {} -- {}", targetIpAddr, pingEntry);
return PollStatus.unknown("ciscoPingTable entry is missing pingCompleted column on proxy interface " + proxyIpAddr + " with instance ID " + pingEntry.getCiscoPingSerialNumber());
}
// mark the service unknown
if (statusValues[5].toInt() != 1) {
LOG.warn("Proxy-ping entry marked not completed after retries exhausted for target {} -- {}", targetIpAddr, pingEntry);
return PollStatus.unknown("ciscoPingTable entry marked not completed on proxy interface " + proxyIpAddr + " with instance ID " + pingEntry.getCiscoPingSerialNumber());
}
// If the ping has completed, verify that the percent of completed pings meets our minimum
// success percent. If not, mark the service down.
double sentPings = statusValues[0].toInt();
double receivedPings = statusValues[1].toInt();
double successPct = receivedPings / sentPings * 100;
if (receivedPings == 0) {
LOG.info("Proxy-ping entry indicates no pings succeeded for target {} -- {}", targetIpAddr, pingEntry);
cleanupCurrentEntry(pingEntry, proxyIpAddr, agentConfig);
return PollStatus.unavailable("All remote pings (" + sentPings + " of " + sentPings + ") failed");
} else if (successPct < minSuccessPercent) {
LOG.info("Proxy-ping entry indicates {}% success, which misses the success-percent target of {}% for target {} -- {}", successPct, minSuccessPercent, targetIpAddr, pingEntry);
cleanupCurrentEntry(pingEntry, proxyIpAddr, agentConfig);
return PollStatus.unavailable(successPct + " percent (" + receivedPings + "/" + sentPings + ") pings succeeded, less than target " + minSuccessPercent + " percent");
}
// If we've arrived here, then enough pings completed to consider the service up!
Map<String, Number> pingProps = new HashMap<String, Number>();
double minRtt = statusValues[2].toInt();
double avgRtt = statusValues[3].toInt();
double maxRtt = statusValues[4].toInt();
LOG.debug("Logging successful poll: sent={}, received={}, minRtt={}, avgRtt={}, maxRtt={} for proxy-ping of target {} -- {}", sentPings, receivedPings, minRtt, avgRtt, maxRtt, targetIpAddr, pingEntry);
pingProps.put("sent", sentPings);
pingProps.put("received", receivedPings);
pingProps.put("minRtt", minRtt);
pingProps.put("avgRtt", avgRtt);
pingProps.put("maxRtt", maxRtt);
cleanupCurrentEntry(pingEntry, proxyIpAddr, agentConfig);
// TODO: Find and clean up defunct rows before returning
// Actually it's not clear that this is necessary, seems IOS cleans up old
// entries on its own some minutes after their creation. Need to investigate.
serviceStatus = PollStatus.available(avgRtt);
serviceStatus.setProperties(pingProps);
return serviceStatus;
}
Aggregations