Search in sources :

Example 31 with TimeoutTracker

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;
}
Also used : PollStatus(org.opennms.netmgt.poller.PollStatus) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) InetAddress(java.net.InetAddress)

Example 32 with TimeoutTracker

use of org.opennms.core.utils.TimeoutTracker in project opennms by OpenNMS.

the class TimeoutTrackerTest method testElapsedTimeButNoStartAttempt.

public void testElapsedTimeButNoStartAttempt() {
    Map<String, ?> emptyMap = Collections.emptyMap();
    TimeoutTracker tracker = new TimeoutTracker(emptyMap, 0, 3000);
    try {
        tracker.elapsedTimeInMillis();
        fail("expected an exception since no startAttempt is called");
    } catch (IllegalStateException e) {
    // w00t..
    }
}
Also used : TimeoutTracker(org.opennms.core.utils.TimeoutTracker)

Example 33 with TimeoutTracker

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;
            final StringBuilder reason = new StringBuilder("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;
}
Also used : MalformedURLException(java.net.MalformedURLException) CIMObject(org.sblim.wbem.cim.CIMObject) PollStatus(org.opennms.netmgt.poller.PollStatus) HostRuntimeInfo(com.vmware.vim25.HostRuntimeInfo) HostSystemPowerState(com.vmware.vim25.HostSystemPowerState) MalformedURLException(java.net.MalformedURLException) RemoteException(java.rmi.RemoteException) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) HostSystem(com.vmware.vim25.mo.HostSystem) RemoteException(java.rmi.RemoteException) VmwareViJavaAccess(org.opennms.protocols.vmware.VmwareViJavaAccess)

Example 34 with TimeoutTracker

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;
}
Also used : MalformedURLException(java.net.MalformedURLException) PollStatus(org.opennms.netmgt.poller.PollStatus) HostRuntimeInfo(com.vmware.vim25.HostRuntimeInfo) VirtualMachineRuntimeInfo(com.vmware.vim25.VirtualMachineRuntimeInfo) HostSystemPowerState(com.vmware.vim25.HostSystemPowerState) VirtualMachinePowerState(com.vmware.vim25.VirtualMachinePowerState) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) HostSystem(com.vmware.vim25.mo.HostSystem) RemoteException(java.rmi.RemoteException) VmwareViJavaAccess(org.opennms.protocols.vmware.VmwareViJavaAccess) VirtualMachine(com.vmware.vim25.mo.VirtualMachine)

Example 35 with TimeoutTracker

use of org.opennms.core.utils.TimeoutTracker in project opennms by OpenNMS.

the class AsteriskSIPPeerMonitor method poll.

/**
 * {@inheritDoc}
 *
 * <P>
 * Run the service monitor and return the poll status
 * </P>
 */
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    // read configuration parameters
    String sipPeer = ParameterMap.getKeyedString(parameters, "sip-peer", DEFAULT_SIPPEER);
    if (sipPeer.equals(DEFAULT_SIPPEER)) {
        LOG.error("AsteriskMonitor: No sip-peer parameter in poller configuration");
        throw new RuntimeException("AsteriskMonitor: required parameter 'sip-peer' is not present in supplied properties.");
    }
    TimeoutTracker timeoutTracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
    AmiPeerFactory amiPeerFactory = AmiPeerFactory.getInstance();
    AmiAgentConfig amiConfig = amiPeerFactory.getAgentConfig(svc.getAddress());
    // setting up AMI connection
    LOG.debug("{}: Creating new AMI-Connection: {}:{}, {}/{}", svc.getSvcName(), svc.getIpAddr(), amiConfig.getPort(), amiConfig.getUsername(), amiConfig.getPassword());
    ManagerConnectionFactory factory = new ManagerConnectionFactory(svc.getIpAddr(), amiConfig.getPort().orElse(null), amiConfig.getUsername().orElse(null), amiConfig.getPassword().orElse(null));
    ManagerConnection managerConnection;
    if (amiConfig.getUseTls().orElse(false)) {
        managerConnection = factory.createSecureManagerConnection();
    } else {
        managerConnection = factory.createManagerConnection();
    }
    managerConnection.setSocketTimeout(new Long(timeoutTracker.getTimeoutInMillis()).intValue());
    // start with polling
    while (timeoutTracker.shouldRetry()) {
        timeoutTracker.nextAttempt();
        LOG.debug("{}: Attempt {}", svc.getSvcName(), timeoutTracker.getAttempt());
        try {
            LOG.debug("{}: AMI login", svc.getSvcName());
            managerConnection.login();
            LOG.debug("{}: AMI sendAction SipShowPeer", svc.getSvcName());
            ManagerResponse response = managerConnection.sendAction(new SipShowPeerAction(sipPeer));
            if (response.getAttribute("Status") == null) {
                LOG.debug("{}: service status down", svc.getSvcName());
                return PollStatus.decode("Down", "State of SIP Peer is unknown, because it was not found on the Asterisk server");
            }
            LOG.debug("{}: Response: {}", svc.getSvcName(), response.getAttribute("Status"));
            LOG.debug("{}: AMI logoff", svc.getSvcName());
            managerConnection.logoff();
            if (response.getAttribute("Status").startsWith("OK")) {
                LOG.debug("{}: service status up", svc.getSvcName());
                return PollStatus.decode("Up", "OK");
            } else {
                LOG.debug("{}: service status down", svc.getSvcName());
                return PollStatus.decode("Down", "State of SIP Peer is " + response.getAttribute("Status") + " and not OK");
            }
        } catch (AuthenticationFailedException e) {
            LOG.debug("{}: AMI AuthenticationError.", svc.getSvcName(), e);
            return PollStatus.decode("Down", "Could not get the state of SIP Peer: AMI AuthenticationError");
        } catch (TimeoutException e) {
            LOG.debug("{}: TimeOut reached.", svc.getSvcName(), e);
        } catch (SocketTimeoutException e) {
            LOG.debug("{}: TimeOut reached.", svc.getSvcName(), e);
        } catch (Exception e) {
            LOG.error("{}: An Unknown Exception Occurred.", svc.getSvcName(), e);
            return PollStatus.decode("Down", "Could not get the state of SIP Peer: " + e.toString());
        }
    }
    // If none of the retries worked
    return PollStatus.decode("Down", "Could not get the state of SIP Peer: Timeout exceeded");
}
Also used : ManagerConnection(org.asteriskjava.manager.ManagerConnection) ManagerResponse(org.asteriskjava.manager.response.ManagerResponse) AuthenticationFailedException(org.asteriskjava.manager.AuthenticationFailedException) ManagerConnectionFactory(org.asteriskjava.manager.ManagerConnectionFactory) AmiAgentConfig(org.opennms.netmgt.config.ami.AmiAgentConfig) SipShowPeerAction(org.asteriskjava.manager.action.SipShowPeerAction) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) TimeoutException(org.asteriskjava.manager.TimeoutException) SocketTimeoutException(java.net.SocketTimeoutException) AuthenticationFailedException(org.asteriskjava.manager.AuthenticationFailedException) SocketTimeoutException(java.net.SocketTimeoutException) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) AmiPeerFactory(org.opennms.netmgt.config.AmiPeerFactory) TimeoutException(org.asteriskjava.manager.TimeoutException) SocketTimeoutException(java.net.SocketTimeoutException)

Aggregations

TimeoutTracker (org.opennms.core.utils.TimeoutTracker)42 PollStatus (org.opennms.netmgt.poller.PollStatus)29 InetAddress (java.net.InetAddress)24 IOException (java.io.IOException)16 InterruptedIOException (java.io.InterruptedIOException)13 ConnectException (java.net.ConnectException)13 NoRouteToHostException (java.net.NoRouteToHostException)13 InetSocketAddress (java.net.InetSocketAddress)11 Socket (java.net.Socket)11 InputStreamReader (java.io.InputStreamReader)7 BufferedReader (java.io.BufferedReader)6 HashMap (java.util.HashMap)4 MalformedURLException (java.net.MalformedURLException)3 Pattern (java.util.regex.Pattern)3 HostRuntimeInfo (com.vmware.vim25.HostRuntimeInfo)2 HostSystemPowerState (com.vmware.vim25.HostSystemPowerState)2 HostSystem (com.vmware.vim25.mo.HostSystem)2 SocketTimeoutException (java.net.SocketTimeoutException)2 RemoteException (java.rmi.RemoteException)2 Properties (java.util.Properties)2